For flags(选项开头为-
or --
) 传入选项with旗帜。您可以指定多个选项:
parser.add_argument('-i', '--inputdir', help="Specify the input directory")
See the 名称或标志选项文档 https://docs.python.org/2/library/argparse.html#name-or-flags:
The add_argument()
方法必须知道是否有可选参数,例如-f
or --foo
,或位置参数,如文件名列表,是预期的。第一个参数传递给add_argument()
因此必须是一系列标志或简单的参数名称。
Demo:
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-i', '--inputdir', help="Specify the input directory")
_StoreAction(option_strings=['-i', '--inputdir'], dest='inputdir', nargs=None, const=None, default=None, type=None, choices=None, help='Specify the input directory', metavar=None)
>>> parser.print_help()
usage: [-h] [-i INPUTDIR]
optional arguments:
-h, --help show this help message and exit
-i INPUTDIR, --inputdir INPUTDIR
Specify the input directory
>>> parser.parse_args(['-i', '/some/dir'])
Namespace(inputdir='/some/dir')
>>> parser.parse_args(['--inputdir', '/some/dir'])
Namespace(inputdir='/some/dir')
然而,第一个元素required参数只是一个占位符。-
and --
选项有always可选(这是命令行约定),必需的参数永远不会用此类开关指定。相反,命令行帮助将显示在何处放置所需参数,并根据传递给的第一个参数使用占位符add_argument()
,传递时不带破折号。
如果您必须打破该约定并使用以-
or --
这是必需的anyway,你必须自己检查:
args = parser.parse_args()
if not args.inputdir:
parser.error('Please specify an inputdir with the -i or --inputdir option')
这里的parser.error() method https://docs.python.org/2/library/argparse.html#argparse.ArgumentParser.error将打印帮助信息以及错误消息,然后退出。