如何在 python 中编写 argparse 组合选项
我一直为完成这个小小的活动而烦恼。我确实做了一些实验,但未能达到结果。
要求:
test2.py [-c/-v] -f
用法或规则:
-c(比较)需要 2 个参数。
-v(验证)采用 1 个参数。
这两者之一必须存在,但不能同时存在。
- -f 是强制参数(输出文件名)。
输出:
我能够获得所需的输出,如下所示
kp@kp:~/Study/scripts$ ./test.py -c P1 P2 -f p
kp@kp:~/Study/scripts$ ./test.py -v P1 -f p
kp@kp:~/Study/scripts$ ./test.py -v P1
usage: test.py <functional argument> <ouput target argument>
test.py: error: argument -f/--file is required
kp@kp:~/Study/scripts$ ./test.py -c P1 P2
usage: test.py <functional argument> <ouput target argument>
test.py: error: argument -f/--file is required
kp@kp:~/Study/scripts$
问题是:
当您使用时,test.py -h
,
1. 输出不会表明 -c/-v 其中任何一个是强制的,但不是两者都强制 。它表示所有参数都是可选的。
2. 输出将指示可选参数下的 -f 选项,这是不正确的。 -f 是强制参数,我想显示外部 - 可选参数。
如何更改脚本以使 -h 选项输出更加用户友好(无需任何外部验证)
usage: test.py <functional argument> <ouput target argument>
Package Compare/Verifier tool.
optional arguments:
-h, --help show this help message and exit
-f outFileName, --file outFileName
File Name where result is stored.
-c Package1 Package2, --compare Package1 Package2
Compare two packages.
-v Package, --verify Package
Verify Content of package.
kiran@kiran-laptop:~/Study/scripts$
代码:
我正在使用以下代码来实现输出,
#!/usr/bin/python
import sys
import argparse
def main():
usage='%(prog)s <functional argument> <ouput target argument>'
description='Package Compare/Verifier tool.'
parser = argparse.ArgumentParser(usage=usage,description=description)
parser.add_argument('-f','--file',action='store',nargs=1,dest='outFileName',help='File Name where result is stored.',metavar="outFileName",required=True)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-c','--compare',action='store',nargs=2,dest='packageInfo',help='Compare two packages.',metavar=("Package1","Package2"))
group.add_argument('-v','--verify',action='store',nargs=1,dest='packageName',help='Verify Content of package.',metavar='Package')
args = parser.parse_args()
if __name__ == "__main__":
main()
I have been troubled with this small piece of activity to be completed. I did do some experiment, but was not able to achieve the result.
Requirement:
test2.py [-c/-v] -f
Usage or Rules:
-c (compare) takes 2 parameter.
-v (verify) takes 1 parameter.
Either of these two must be present, but not both.
- -f is a mandatory parameter (output file name).
Output:
I am able to get the desired output as shown below
kp@kp:~/Study/scripts$ ./test.py -c P1 P2 -f p
kp@kp:~/Study/scripts$ ./test.py -v P1 -f p
kp@kp:~/Study/scripts$ ./test.py -v P1
usage: test.py <functional argument> <ouput target argument>
test.py: error: argument -f/--file is required
kp@kp:~/Study/scripts$ ./test.py -c P1 P2
usage: test.py <functional argument> <ouput target argument>
test.py: error: argument -f/--file is required
kp@kp:~/Study/scripts$
Problem is:
When you use, test.py -h
,
1. The output will not indicate that -c/-v either of them is mandatory but not both . It indicates all the arguments are optional.
2. The output will indicate -f option under optional arguments which is incorrect. -f is mandatory argument, and I want to display outside - optional arguments.
How to change the script so that -h option output will be more user friendly (without any external validation)
usage: test.py <functional argument> <ouput target argument>
Package Compare/Verifier tool.
optional arguments:
-h, --help show this help message and exit
-f outFileName, --file outFileName
File Name where result is stored.
-c Package1 Package2, --compare Package1 Package2
Compare two packages.
-v Package, --verify Package
Verify Content of package.
kiran@kiran-laptop:~/Study/scripts$
Code:
I am using the below code to achieve the output,
#!/usr/bin/python
import sys
import argparse
def main():
usage='%(prog)s <functional argument> <ouput target argument>'
description='Package Compare/Verifier tool.'
parser = argparse.ArgumentParser(usage=usage,description=description)
parser.add_argument('-f','--file',action='store',nargs=1,dest='outFileName',help='File Name where result is stored.',metavar="outFileName",required=True)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-c','--compare',action='store',nargs=2,dest='packageInfo',help='Compare two packages.',metavar=("Package1","Package2"))
group.add_argument('-v','--verify',action='store',nargs=1,dest='packageName',help='Verify Content of package.',metavar='Package')
args = parser.parse_args()
if __name__ == "__main__":
main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将文件名设置为位置参数,并让 argparse 设置其自己的使用消息:
文件名应该是位置的,并且您应该让 argparse 编写其自己的使用消息。
代码
帮助消息
Set the filename to be a positional argument, and let
argparse
set its own usage message:The filename should be positional, and you should let
argparse
write its own usage message.Code
Help message
您正在寻找什么确切的输出?我不知道有任何标准语法可以在 --help 输出中表示相互排他性,如果您编造了一种语法,可能会让您的用户感到困惑。另外,我假设 argparse 不支持它的语法(因为如果支持,它就已经可以工作了)。
我建议您保持简单,只需在每个参数的帮助中向用户解释互斥。因此,将其帮助字符串更改如下:
这是非常明显且相当简洁的。
另一种选择是不提及它,并让用户通过尝试同时使用它们来发现它们是互斥的(argparse 自动生成一个用户友好的错误,例如“
PROG: error: argument -c: not允许使用参数 -v
")。What exact output are you looking for? I am not aware of any standard syntax for denoting mutual exclusitivity in a --help output, and it would likely be confusing for your users if you made one up. Also I assume that argparse doesn't support a syntax for it (since if it did, it would already be working).
I suggest you keep it simple and just explain to your users the mutual exclusion in the help for each of the arguments. So change their help strings as follows:
That is extremely obvious and reasonably concise.
Another alternative would be just to not mention it, and have the user discover that they are mutually exclusive by trying to use them simultaneously (argparse automatically generates a user-friendly error such as "
PROG: error: argument -c: not allowed with argument -v
").我认为基本的抱怨是默认的位置参数和可选参数组名称。在
帮助
中,可选参数
表示:需要像-f或--file这样的标志
;位置参数
意味着它由位置标识
。使用默认值时,positionals
确实是必需的,options
确实是可选的(不是必需的)。但用户可以使用required
属性更改它,从而导致术语混乱。解决这个问题的方法是定义您自己的参数组。这些组会影响
帮助
的布局,但对解析没有影响。它们也不会影响usage
行。产生:
mutually_exclusive_group
仅影响usage
行。显示需要其中一个选项的组。
将是一个可选组。
[]
用于标记可选(在“非必需”意义上)参数。请注意-h
是如何继续被标记的。http://bugs.python.org/issue9694 是相关的 Python 问题,其中 argparse 作者赞成这种
argument_group
方法。I think the basic complaint is with the default
positional arguments
andoptional arguements
group names. In thehelp
,optional arguments
means:requires a flag like -f or --file
;positional arguments
meansit is identified by position
. With default values,positionals
are indeed required, andoptionals
are indeed optional (not required). But the user can change that with arequired
attribute, giving rise to confusing terminology.A way around this is to define your own argument groups. These groups affect the layout of the
help
, but have no effect on parsing. They also don't affect theusage
line.produces:
The
mutually_exclusive_group
affects only theusage
line.displays a group where one of the choices is required.
would be an optional group.
[]
are used to mark optional (in the 'not required' sense) arguments. Note how-h
continues to be labeled.http://bugs.python.org/issue9694 is the related Python issue, where the
argparse
author favors thisargument_group
approach.