Python argparse检查是否存在标志,同时还允许参数 [英] Python argparse check if flag is present while also allowing an argument
问题描述
如何检查标志--load
是否存在?
How do I check if the flag --load
is present?
#!/usr/bin/env python3
import argparse
import os
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-l', '--load', nargs='?', metavar='path', help='Load all JSON files recursively in path')
args = parser.parse_args()
print(args)
使用--load
调用脚本将输出以下内容:
Namespace(load=None)
Calling the script with --load
outputs the following:
Namespace(load=None)
我不能省略nargs='?'
并使用action='store_true'
,因为我想允许传递参数,例如--load abcxyz
.
I can't omit nargs='?'
and use action='store_true'
as I'd like to allow an argument to be passed, for example --load abcxyz
.
添加action='store_true'
和nargs='?'
会产生以下错误:
Adding action='store_true'
and nargs='?'
produces an error of:
parser.add_argument('-l', '--load', nargs='?', metavar='path', help='Load all JSON files recursively in path', action='store_true')
File "/usr/lib/python3.6/argparse.py", line 1334, in add_argument
action = action_class(**kwargs)
TypeError: __init__() got an unexpected keyword argument 'nargs'
推荐答案
在上述片段中,用于检查--load标志:
In the same above snippet, for checking --load flag:
#!/usr/bin/env python3
import argparse
import os
name = None
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-l', '--load', metavar='path', help='Load all JSON
files recursively in path')
args = parser.parse_args()
print(args.load)
if args.load:
name = args.load
将name
分配给abcxyz
,否则将为空.
如果我能够理解您的问题,那么上面的代码实际上可以满足您的需求.
name
变量并不是真正需要的,仅作为示例.
will assign name
to abcxyz
, else will be none.
If i am able to understand your problem, the above code actually does what you are looking for.
The name
variable is not really required , just used as an example.
这篇关于Python argparse检查是否存在标志,同时还允许参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!