[英]Store values of mutually exclusive options in same argument in Python argparse
I have a Python script that can deploy some software in three different environments, let's call them development
, testing
and production
.我有一个 Python 脚本,它可以在三种不同的环境中部署一些软件,我们称它们为development
、 testing
和production
。 In order to select which environment the script should work with, I want to use mutually exclusive flags, like so:为了选择脚本应该使用的环境,我想使用互斥标志,如下所示:
./deploy.py --development
./deploy.py --testing
./deploy.py --production
So far I have this:到目前为止,我有这个:
parser = argparse.ArgumentParser(description="Manage deployment")
group = parser.add_mutually_exclusive_group()
group.add_argument("-d", "--development", action='store_true', required=False)
group.add_argument("-t", "--testing", action='store_true', required=False)
group.add_argument("-p", "--production", action='store_true', required=False)
args = parser.parse_args()
Thing is, I want to have the environment in a single variable, so I can easily check it, instead of having to manually check args.development
, args.testing
and args.production
.事实是,我想将环境放在一个变量中,这样我就可以轻松检查它,而不必手动检查args.development
、 args.testing
和args.production
。
Is there a way of having a common variable that the three arguments could write to so I could do something like args.environment
?有没有办法让三个参数可以写入一个公共变量,这样我就可以做类似args.environment
事情?
Instead of using action='store_true'
, you can use action='store_const'
, assign an individual const
value for each argument and the dest
option of add_argument
, so that all the arguments in the mutually exclusive group have the same destination in the object returned by parse_args
.而不是使用的action='store_true'
,你可以用action='store_const'
,分配一个单独的const
为每个参数和值dest
的选项add_argument
,这样在相互排斥的组中的所有参数都在对象相同的目的地由parse_args
返回。
parser = argparse.ArgumentParser(description="Manage deployment")
group = parser.add_mutually_exclusive_group()
group.add_argument("-d", "--development", action='store_const', dest='environment', const='development', required=False)
group.add_argument("-t", "--testing", action='store_const', dest='environment', const='testing', required=False)
group.add_argument("-p", "--production", action='store_const', dest='environment', const='production', required=False)
args = parser.parse_args()
print(args)
The output is:输出是:
$ ./test_args.py --production
Namespace(environment='production')
Instead of 3 arguments, you can just use one with choices :您可以只使用一个带有选择的参数,而不是 3 个参数:
parser = argparse.ArgumentParser(description="Manage deployment")
parser.add_argument("environment", choices=['development', 'testing', 'production'])
args = parser.parse_args()
print(args)
Examples:例子:
>>> test_args.py
usage: concept.py [-h] {development,testing,production}
test_args.py: error: the following arguments are required: environment
>>> test_args.py testing
Namespace(environment='testing')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.