对于 flags(以 - 或 -- 开头的选项)传入选项 with 标志。您可以指定多个选项:
parser.add_argument('-i', '--inputdir', help="Specify the input directory")
见name or flags option documentation:
add_argument() 方法必须知道是否需要可选参数(如 -f 或 --foo)或位置参数(如文件名列表)。因此,传递给add_argument() 的第一个参数必须是一系列标志,或者是一个简单的参数名称。
演示:
>>> 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 参数的第一个元素只是一个占位符。 - 和-- 选项总是 可选(这是命令行约定),从不使用此类开关指定必需的参数。相反,命令行帮助将根据传递给 add_argument() 的第一个参数显示所需参数的放置位置,占位符将不带破折号传入。
如果您必须打破该约定并使用以- 或-- 开头的参数无论如何,您必须自己进行检查:
args = parser.parse_args()
if not args.inputdir:
parser.error('Please specify an inputdir with the -i or --inputdir option')
这里parser.error() method会打印帮助信息和你的错误信息,然后退出。