Python argparse允许组合标志 [英] Python argparse allow combined flags
问题描述
argparse是否可以像这样分析组合标志:
Is it possible for argparse to parse combined flags like this:
app.py -bcda something
在这种情况下,我希望将 something
设置为 -a
,其余的存储为True.基本上:
In this case, I would want something
to be set to -a
and the rest would be stored True. Basically:
app.py -b -c -d -a something
我知道大多数程序都允许这样做,例如 grep -rEw
,但是用argparse做到这一点有多困难?
I know most programs allow this, e.g. grep -rEw
, but how hard would it be to do this with with argparse?
推荐答案
您可以使用store_const来实现:
You can achieve this with store_const:
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store_const', const=True, default=False)
parser.add_argument('-b', action='store_const', const=True, default=False)
args = parser.parse_args()
然后您可以使用 -a -b
或 -ab
(或 -a
或 -b
).
Then you can call this from the command line either with -a -b
or with -ab
(or -a
, or -b
).
如果您希望其中一个标志作为参数,则需要将其作为链的最后一项传递.因此,如果 a
接受参数,则需要做 -bcda某事
and if you want one of the flags to take an argument, you need to pass it as the last item of the chain. So if a
takes an argument, you'd need to do -bcda something
这篇关于Python argparse允许组合标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!