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

问题描述

我想为我的程序设置一个参数,该参数包含一些必需参数和一些可选参数.像这样:

[--print text [color [size]]

所以你可以通过以下任何一个:

mycommand --print hellomycommand --print hello bluemycommand --print hello red 12

这些可能有多个,所以它必须是一个 add_argument.例如:

[--print text [color]] [--output filename [overwrite]]

我可以实现接近我想要的参数:

>>>解析器 = argparse.ArgumentParser()>>>act = parser.add_argument('--foo', nargs=3, metavar=('x','y','z'))>>>act = parser.add_argument('--bar', nargs='?')>>>act = parser.add_argument('--baz', nargs='*')>>>parser.print_help()用法:[-h] [--foo x y z] [--bar [BAR]] [--baz [BAZ [BAZ ...]]]可选参数:-h, --help 显示此帮助信息并退出--foo x y z--bar [酒吧]--baz [BAZ [BAZ ...]]

但不完全是.有没有办法用 argparse 做到这一点?我知道我可以将它们全部设为 nargs="*" 但随后 --help 不会列出可选参数的名称.如果我传递 nargs="*" 和元组元组,argparse 会抛出异常.

解决方案

阅读源代码(从take_action开始),我相信你想要的是不可能的.所有参数解析和传递给动作都是基于 nargs 完成的,nargs 要么是一个数字,OPTIONAL ("?"), ZERO_OR_MORE ("*"), ONE_OR_MORE(+")、PARSERREMAINDER.这必须在 Action 对象(处理输入)甚至看到它得到什么之前确定,所以它不能动态地找出 nargs.

我认为您需要接受一种解决方法.我可能有 --foo-x x--foo-y y--foo-z z,也许还有--foo xyz.

I'd like to have an argument to my program that has some required parameters along with some optional parameters. Something like this:

[--print text [color [size]]

so you could pass it any of these:

mycommand --print hello
mycommand --print hello blue
mycommand --print hello red 12

There could be multiple of these so it has to be a single add_argument. For example:

[--print text [color]] [--output filename [overwrite]]

I can achieve arguments that are close to what I want:

>>> parser = argparse.ArgumentParser()
>>> act = parser.add_argument('--foo', nargs=3, metavar=('x','y','z'))
>>> act = parser.add_argument('--bar', nargs='?')
>>> act = parser.add_argument('--baz', nargs='*')
>>> parser.print_help()
usage: [-h] [--foo x y z] [--bar [BAR]] [--baz [BAZ [BAZ ...]]]

optional arguments:
  -h, --help            show this help message and exit
  --foo x y z
  --bar [BAR]
  --baz [BAZ [BAZ ...]]

but not quite. Is there any way to do this with argparse? I know I could make them all nargs="*" but then --help would not list the names of the optional arguments. If I pass nargs="*" and a tuple for metavar, argparse throws an exception.

解决方案

Reading the source code (start in take_action), I believe what you want is impossible. All argument parsing and passing to actions is done based on nargs, and nargs is either a number, OPTIONAL ("?"), ZERO_OR_MORE ("*"), ONE_OR_MORE ("+"), PARSER, or REMAINDER. This must be determined before the Action object (which handles the input) even sees what it's getting, so it can't dynamically figure out nargs.

I think you'll need to live with a workaround. I would maybe have --foo-x x, --foo-y y, and --foo-z z, and perhaps also --foo x y z.

这篇关于Python argparse 可选子参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 22:08