argparse:使用必需参数的值设置可选参数 [英] argparse: setting optional argument with value of mandatory argument
问题描述
使用Python的 argparse ,我想添加一个可选参数,如果没有给出该参数,另一个(强制性)参数的值.
With Python's argparse, I would like to add an optional argument that, if not given, gets the value of another (mandatory) argument.
parser.add_argument('filename',
metavar = 'FILE',
type = str,
help = 'input file'
)
parser.add_argument('--extra-file', '-f',
metavar = 'ANOTHER_FILE',
type = str,
default = ,
help = 'complementary file (default: FILE)'
)
我当然可以在解析参数之后手动检查None
,但是没有更Python的方式可以做到这一点吗?
I could of course manually check for None
after the arguments are parsed, but isn't there a more pythonic way of doing this?
推荐答案
据我所知,没有比这更干净的方法了:
As far as I know, there is no way to do this that is more clean than:
ns = parser.parse_args()
ns.extra_file = ns.extra_file if ns.extra_file else ns.filename
(就像您在问题中提出的一样).
(just like you propose in your question).
您可以可能会做一些与此类似的自定义动作体操,但是我真的不知道认为那是不值得的(或"pythonic").
You could probably do some custom action gymnastics similar to this, but I really don't think that would be worthwhile (or "pythonic").
这篇关于argparse:使用必需参数的值设置可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!