Python argparse:如何在仍为可选参数的情况下将--add更改为add? [英] Python argparse: How to change `--add` into `add` while still being an optional argument?
本文介绍了Python argparse:如何在仍为可选参数的情况下将--add更改为add?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要此功能:
$ python program.py add Peter
'Peter' was added to the list of names.
我可以使用--add
而不是add
来实现这一点:
I can achieve this with --add
instead of add
like this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--add", help="Add a new name to the list of names",
action="store")
args = parser.parse_args()
if args.add:
print "'%s' was added to the list of names." % args.add
else:
print "Just executing the program baby."
如此:
$ python program.py --add Peter
'Peter' was added to the list of names.
但是当我将--add
更改为add
时,它不再是可选的,我如何仍可以使它成为可选的而又没有这些--
的标志呢? (最好也使用argparse
库)
But when I change --add
to add
it is no longer optional, how can I still let it be optional yet not have those --
signs? (preferably also using the argparse
library)
推荐答案
您想要的实际上称为位置参数". 您可以这样解析它们:
What you want, is actually called "positional arguments". You can parse them like this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("cmd", help="Execute a command",
action="store", nargs='*')
args = parser.parse_args()
if args.cmd:
cmd, name = args.cmd
print "'%s' was '%s'-ed to the list of names." % (name, cmd)
else:
print "Just executing the program baby."
您可以通过它指定不同的操作:
Which gives you the ability to specify different actions:
$ python g.py add peter
'peter' was 'add'-ed to the list of names.
$ python g.py del peter
'peter' was 'del'-ed to the list of names.
$ python g.py
Just executing the program baby.
这篇关于Python argparse:如何在仍为可选参数的情况下将--add更改为add?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文