python argparse可选参数的默认值 [英] python argparse default value for optional argument
问题描述
usage: [-h] [--foo FOO] bar
- 如果执行如下所示的脚本,如何确保FOO的默认值为
abc
./myscript.py --foo bar
-> bar
是位置参数.但是args.foo
正在考虑将bar
作为'--foo'
的参数.我希望args.foo
是abc
,而bar
是位置参数
./myscript.py --foo bar
--> bar
is positional argument here. but args.foo
is considering bar
as argument of '--foo'
. I want args.foo
to be abc
and bar
to be the positional argument
推荐答案
您不能,除非不修改参数.
You can't, not without reworking your arguments.
您应该在此处使用两个开关;一种打开行为,另一种覆盖选择的默认值.您可以使第二个开关隐含第一个开关:
You should use two switches here; one to switch on the behaviour, and one to override the default value picked. You can make the second switch imply the first:
usage: [-h] [--foo] [--foo-setting FOO] bar
其中--foo
是用于切换行为的布尔开关,而--foo-setting
可让您设置开关的配置:
where --foo
is a boolean switch that toggles the behaviour, and --foo-setting
lets you set the configuration for the switch:
parser.add_argument('--foo', action='store_true')
parser.add_argument('--foo-setting', help='Set the value for foo, implies --foo is given')
# ...
args = parser.parse_args()
if args.foo_setting is not None:
# default was overridden, explicitly enable the foo feature
args.foo = True
if args.foo:
foo_feature_setting = args.foo_setting or 'default value'
这篇关于python argparse可选参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!