简体   繁体   English

argparse:使用必需参数的值设置可选参数

[英]argparse: setting optional argument with value of mandatory argument

With Python's argparse , I would like to add an optional argument that, if not given, gets the value of another (mandatory) argument. 使用Python的argparse ,我想添加一个可选参数,如果没有给出,则获取另一个(强制)参数的值。

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)'
                    )

I could of course manually check for None after the arguments are parsed, but isn't there a more pythonic way of doing this? 我当然可以在解析参数后手动检查None ,但是不是有更多的pythonic方法吗?

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). (就像你提出的问题一样)。

You could probably do some custom action gymnastics similar to this , but I really don't think that would be worthwhile (or "pythonic"). 可能会做一些与此类似的自定义动作体操 ,但我真的不认为这是值得的(或“pythonic”)。

This has slightly different semantics than your original set of options, but may work for you: 这与原始选项集的语义略有不同,但可能对您有用:

parse.add_argument('filename', action='append', dest='filenames')
parse.add_argument('--extra-file', '-f', action='append', dest='filenames')
args = parse.parse_args()

This would replace args.filename with a list args.filenames of at least one file, with -f appending its argument to that list. 这将使用至少一个文件的列表args.filenames替换args.filename ,其中-f将其参数附加到该列表。 Since it's possible to specify -f on the command line before the positional argument, you couldn't on any particular order of the input files in args.filenames . 由于可以在位置参数之前在命令行上指定-f ,因此您无法在args.filenames输入文件的任何特定顺序。


Another option would be to dispense with the -f option and make filename a multi-valued positional argument: 另一种选择是省去-f选项并使filename成为多值位置参数:

parse.add_argument('filenames', nargs='+')

Again, args.filenames would be a list of at least one filename. 同样, args.filenames将是至少一个文件名的列表。 This would also interfere if you have other positional arguments for your script. 如果你的脚本有其他位置参数,这也会干扰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM