Python argparse:如何在仍然是可选参数的情况下将`--add`更改为`add`? [英] Python argparse: How to change `--add` into `add` while still being an optional argument?

查看:27
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆