问题描述
我有一个使用默认名称和密码的程序.我正在使用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-要么都是可选参数,要么都不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!