Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse: How to accept arguments that have different "types"

I want to accept arguments in the following style:

python3 test.py -r SERVICE=100,101,102 -r SERVICE2=1,2,3,4,5 
(-r REPO=REV#,REV#,etc... -r etc...)

I've done the following so far (added the argument -r and defined the type revs). It's supposed to pass back two lists, which may be problematic.

import argparse

def revs(s):
    try:            
        REPO, REVISIONS = map(str, s.split('='))
        REVISIONS = map(int, REVISIONS.split(','))
        return REPO, REVISIONS
    except:
        raise argparse.ArgumentTypeError("Must be format -r REPO=REV,REV,etc.. e.g. SERVICES=181449,181447") 

parser.add_argument('-r', type='revs', nargs='*', action='append', help='Revisions to update. The list is prefixed with the name of the source repository and a "=" sign. This parameter can be used multiple times.', required=True)

I get the following error when running with the above:

Traceback (most recent call last):
File "test.py", line 11, in <module>
parser.add_argument('-r', type='revs', nargs='*', action='append', help='Revisions to update. The list is prefixed with the name of the source repository and a "=" sign. This parameter can be used multiple times.', required=True)
File "/usr/local/lib/python3.3/argparse.py", line 1317, in add_argument
raise ValueError('%r is not callable' % (type_func,))

ValueError: 'revs' is not callable

like image 699
imagineerThat Avatar asked Mar 12 '13 03:03

imagineerThat


People also ask

Does Argparse use SYS argv?

Python argparse The argparse module makes it easy to write user-friendly command-line interfaces. It parses the defined arguments from the sys. argv . The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments.

What does DEST mean in Argparse?

dest is equal to the first argument supplied to the add_argument() function, as illustrated. The second argument, radius_circle , is optional. A long option string --radius supplied to the add_argument() function is used as dest , as illustrated.

What is the difference between Optparse and Argparse?

One area in which argparse differs from optparse is the treatment of non-optional argument values. While optparse sticks to option parsing, argparse is a full command-line argument parser tool, and handles non-optional arguments as well.


1 Answers

you want

parser.add_argument('-r', type=revs, ...)

not

parser.add_argument('-r', type='revs', ...)

The type argument must be a callable object -- since strings aren't callable, they can't be used as the type.

like image 87
mgilson Avatar answered Sep 20 '22 11:09

mgilson