ArgumentParser() 参数详解

# 创建参数解析器
parser = argparse.ArgumentParser(description='程序描述')

比较有用的一些参数:

description: A description of what the program does (程序的描述信息,显示在帮助文档开头)
usage: A usage message (default: auto-generated from arguments)(不建议修改)
formatter_class: HelpFormatter class for printing help messages
	# RawDescriptionHelpFormatter 保留 description 和 epilog 的原始换行格式。
	# RawTextHelpFormatter help.同上
	# ArgumentDefaultsHelpFormatter 在帮助信息中自动显示参数的默认值。
	# MetavarTypeHelpFormatter 用参数的类型名(如 int、str)替代大写的参数名作为 metavar
	# 也可以自定义格式
	# 组合使用: 
	# class CustomFormatter(
	#     ArgumentDefaultsHelpFormatter,
	#     RawDescriptionHelpFormatter
	# ):
	#     pass
	# 然后 formatter_class=CustomFormatter
epilog: Text following the argument descriptions(显示在帮助信息的最后)
	# epilog="示例用法:\n  python demo.py --input data.txt --output result.txt"

图片.png

add_argument() 参数详解

用于添加命令行参数,主要分为:

  • 位置参数(必选参数,如 input_file
  • 可选参数(以 --- 开头的参数,如 --output

基本参数

参数说明示例
name/flags参数名(--output)或位置参数名(input_file"--output""input_file"
action参数的动作(如存储值、布尔开关等)action="store_true"
nargs参数的个数nargs="+"(1个或多个)
constactionnargs 需要的常量值const=42
default默认值default="output.txt"
type参数类型(如 int, float, strtype=int
choices允许的参数值列表choices=["a", "b", "c"]
required是否必须(对可选参数)required=True
help参数的帮助信息help="Output file path"
metavar在帮助信息中显示的参数名称metavar="FILE"
dest解析后存储的属性名dest="output_file"