python3---argparse
python3---argparse
argparse用于设计、解析命令行参数。
官方文档: https://docs.python.org/3/library/argparse.html
一个求和示例:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
更多功能的示例:
# coding:utf8
import argparse
import os
import textwrap
def valid_path(the_path):
if not os.path.exists(the_path):
msg = f"{the_path} does not exist"
raise argparse.ArgumentTypeError(msg)
if not os.path.isfile(the_path):
msg = f"{the_path} is not a file"
raise argparse.ArgumentTypeError(msg)
return the_path
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent(
"""\
A simple description
Example:
python %(prog)s download hello.txt -d 2222_folder -v
python %(prog)s download hello.txt -v
"""
),
)
parser.add_argument("action", choices=["all", "download", "extract", "statistic"])
parser.add_argument("src_path", type=valid_path, help="the source path")
# "-"开头为可选项,可通过"required=True"设置为必选项
parser.add_argument(
"-d", "--dst_path", type=str, default="result_fodler", help="the result folder"
)
parser.add_argument("-v", "--verbose", action="store_true", help="print more info")
args = parser.parse_args()
print(args)
action = args.action
src_path = args.src_path
dst_path = args.dst_path
verbose_flag = args.verbose
# ...
if __name__ == "__main__":
main()
2019/12/1
有些东西,分享就好
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异