可选参数的python argparse默认值 [英] python argparse default value for optional argument

查看:39
本文介绍了可选参数的python argparse默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

usage:  [-h] [--foo FOO] bar

  1. 如果我执行如下脚本,如何确保 FOO 的默认值为 abc

./myscript.py --foo bar --> bar 这里是位置参数.但是 args.foo 正在考虑将 bar 作为 '--foo' 的参数.我希望 args.fooabc 并且 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆