我想要这个功能:
$ python program.py add Peter
'Peter' was added to the list of names.
我可以通过以下方式实现这一点--add
代替add
像这样:
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
to add
它不再是可选的,我怎么能让它仍然是可选的却没有那些--
迹象? (最好也使用argparse
图书馆)
你想要的,实际上叫做“位置参数”。
你可以这样解析它们:
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."
这使您能够指定不同的操作:
$ 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)