python argparse - 要么是可选参数要么都不是 [英] python argparse - either both optional arguments or else neither one
问题描述
我有一个使用默认名称和密码的程序.我正在使用 argparse 来允许用户指定命令行选项,并且我想让用户为程序提供不同的名称和密码以供使用.所以我有以下几点:
I have a program that uses a default name and password. I'm using argparse to allow the user to specify command line options, and I would like to enable the user to provide the program with a different name and password to use. So I have the following:
parser.add_argument(
'-n',
'--name',
help='the login name that you wish the program to use'
)
parser.add_argument(
'-p',
'--password',
help='the password to log in with.'
)
但是只指定名称或只指定密码没有任何意义,但不指定任何一个都有意义.我注意到 argparse 确实能够指定两个参数是互斥的.但我所拥有的是必须同时出现的两个论点.我如何获得这种行为?(我发现文档中提到了参数组",但它们似乎没有解决我的问题 http://docs.python.org/2/library/argparse.html#argument-groups)
But it doesn't make any sense to specify only the name or only the password, but it would make sense to specify neither one. I noticed that argparse does have the ability to specify that two arguments are mutually exclusive. But what I have are two arguments that must appear together. How do I get this behavior? (I found "argument groups" mentioned in the docs, but they don't appear to solve my problem http://docs.python.org/2/library/argparse.html#argument-groups)
推荐答案
我相信处理这个问题的最好方法是对返回的命名空间进行后处理.argparse
不支持这一点的原因是它一次解析参数 1.argparse
很容易检查是否已经解析了某些内容(这就是互斥参数起作用的原因),但要查看某些内容是否将解析并不容易将来解析.
I believe that the best way to handle this is to post-process the returned namespace. The reason that argparse
doesn't support this is because it parses arguments 1 at a time. It's easy for argparse
to check to see if something was already parsed (which is why mutually-exclusive arguments work), but it isn't easy to see if something will be parsed in the future.
一个简单的:
parser.add_argument('-n','--name',...,default=None)
parser.add_argument('-p','--password',...,default=None)
ns = parser.parse_args()
if len([x for x in (ns.name,ns.password) if x is not None]) == 1:
parser.error('--name and --password must be given together')
name = ns.name if ns.name is not None else "default_name"
password = ns.password if ns.password is not None else "default_password"
好像就够了.
这篇关于python argparse - 要么是可选参数要么都不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!