Optional python arguments without a dash, but with extra parameters?

what I would like to do in Python takes arguments of the following format:

script.py START | STOP | STATUS | MOVEABS <x> <y> | MOVEREL <x> <y>

So, in other words,

  • I do not want to deal with hyphens;
  • I have several options, ONE of which is required;
  • Each of them is mutually exclusive;
  • Some of the commands (EG moveabs and moverel) have additional necessary arguments, but these arguments should not be present with any other argument.

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

+4
source share
2 answers

argparser with the steers will 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)

creating similar:

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

and

2146:~/mypy$ python2.7 stack23304740.py MOVEREL 1.0 2.0
...
Namespace(cmd='MOVEREL', x=1.0, y=2.0)

and

2147:~/mypy$ python2.7 stack23304740.py START
...
Namespace(cmd='START')

MOVEREL <x> <y>, args['<y>'] args.y. metavar='<x>' , .

spp.add_argument('point', nargs=2, type=float). , , nargs=2, http://bugs.python.org/issue14074.

+3

docopt, .

docopt:

$ pip install docopt

script.py:

"""
Usage:
    script.py (start | stop | status | moveabs <x> <y> | moverel <x> <y>)
"""
from docopt import docopt

if __name__ == "__main__":
    args = docopt(__doc__)
    print args

:

:

$ python script.py
Usage:
    script.py (start | stop | status | moveabs <x> <y> | moverel <x> <y>)

:

$ python script.py start
{'<x>': None,
 '<y>': None,
 'moveabs': False,
 'moverel': False,
 'start': True,
 'status': False,
 'stop': False}

$ python script.py stop
{'<x>': None,
 '<y>': None,
 'moveabs': False,
 'moverel': False,
 'start': False,
 'status': False,
 'stop': True}

moveabs

$ python script.py moveabs 11 22
{'<x>': '11',
 '<y>': '22',
 'moveabs': True,
 'moverel': False,
 'start': False,
 'status': False,
 'stop': False}

moverel

$ python script.py moverel 11 22
{'<x>': '11',
 '<y>': '22',
 'moveabs': False,
 'moverel': True,
 'start': False,
 'status': False,
 'stop': False}
+4

Source: https://habr.com/ru/post/1538150/


All Articles