问题描述
我想在 Python 中做的是接受以下格式的参数:
what I'd like to do in Python is accept arguments of the following format:
script.py START | STOP | STATUS | MOVEABS <x> <y> | MOVEREL <x> <y>
换句话说,
- 我不想处理连字符;
- 我有多种可能性,其中一种是必需的;
- 每一个都是互斥的;
- 某些命令(例如 moveabs 和 moverel)具有额外的必需参数,但这些参数不应与任何其他参数一起出现.
这可以在 python 中完成吗,我会使用 argparse 还是其他什么?谢谢.
Can this be done in python and would I use argparse or something else? Thanks.
推荐答案
add_parser
使用子解析器可以解决问题
add_parser
with subparsers would do the trick
import argparse
parser = argparse.ArgumentParser(prog='script.py')
sp = parser.add_subparsers(dest='cmd')
for cmd in ['START', 'STOP', 'STATUS']:
sp.add_parser(cmd)
for cmd in ['MOVEABS', 'MOVEREL']:
spp = sp.add_parser(cmd)
spp.add_argument('x', type=float)
spp.add_argument('y', type=float)
parser.print_help()
args = parser.parse_args()
print(args)
生产如下:
2137:~/mypy$ python2.7 stack23304740.py MOVEREL -h
usage: script.py [-h] {START,STOP,STATUS,MOVEABS,MOVEREL} ...
positional arguments:
{START,STOP,STATUS,MOVEABS,MOVEREL}
optional arguments:
-h, --help show this help message and exit
usage: script.py MOVEREL [-h] x y
positional arguments:
x
y
optional arguments:
-h, --help show this help message and exit
和
2146:~/mypy$ python2.7 stack23304740.py MOVEREL 1.0 2.0
...
Namespace(cmd='MOVEREL', x=1.0, y=2.0)
和
2147:~/mypy$ python2.7 stack23304740.py START
...
Namespace(cmd='START')
MOVEREL 参数可以命名为 <x>
和 <y>
,但是你必须通过 args['<y>']
而不是 args.y
.metavar='<x>'
可用于更改显示,但不能用于更改命名空间名称.
The MOVEREL arguments could be named <x>
and <y>
, but then you'd have to access them via args['<y>']
instead of args.y
. metavar='<x>'
could be used to change the display but not the Namespace name.
您也可以使用 spp.add_argument('point', nargs=2, type=float)
.不幸的是,在这个 nargs=2
案例中,有一个错误使我们无法使用元变量,http://bugs.python.org/issue14074.
You could also use spp.add_argument('point', nargs=2, type=float)
. Unfortunately there's a bug that keeps us from using a metavar in this nargs=2
case, http://bugs.python.org/issue14074.
这篇关于没有破折号但有附加参数的可选python参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!