可选的python参数,不带破折号,但带有附加参数? [英] optional python arguments without dashes but with additional parameters?

查看:84
本文介绍了可选的python参数,不带破折号,但带有附加参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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>

换句话说

  1. 我不想处理连字符;
  2. 我有多种可能性,其中之一是必需的;
  3. 每个都是互斥的;
  4. 某些命令(例如moveabs和moverel)具有其他必需的参数,但是这些args不应与其他任何参数一起出现.

这可以在python中完成吗,我会使用argparse或其他方法吗?谢谢.

Can this be done in python and would I use argparse or something else? Thanks.

推荐答案

add_parser可以解决问题

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情况下使用metavar,即 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参数,不带破折号,但带有附加参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆