可选参数的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屋!