2

I would like to know if its possible to use argparse to add a feature to a script I have written to make REST requests. The current usage works great and looks like this:

$./prog.py -h
usage: prog.py [-h] [--headers [HEADER [HEADER ...]]]
                  [--queryparams [QUERY [QUERY ...]]] [--body [BODY]]
                  [METHOD] URL

I get that usage with something like this:

parser = argparse.ArgumentParser()

position = self.parser.add_argument_group(
    title='Positional arguments',
    description='The only required argument is URL.'
)

position.add_argument(...)
position.add_argument(...)

What I want to do is add a second group of parameters that is totally mutually exclusive from the first group.

The usage for the second group will look something like this:

$./prog.py -h
usage: restcli.py [-h] request {refresh,update}

That is, if request is the first argument then the only valid option along with it is refresh or update. If request isn't the first parameter assume that we are dealing with the orginal usage.

I think with subparsers I could almost do this but it would require a keyword to specify that I want the original non-request parser. A usage in that case might look like this but I want to avoid that original keyword if possible:

$ ./prog.py -h
usage: prog.py [-h] {orignal,request} 

Thanks in advance for any help you may be able to provide.

jay
  • 53
  • 1
  • 5
  • I'd recommend making a link/symlink to the program and checking `os.path.basename(sys.argv[0])` to decide how to behave, instead. Invoked under the "old" name, do the old stuff; under the new name, have new, different argument parsng. – torek Aug 05 '13 at 00:40
  • 1
    [Does argparse python support mutually exclusive groups of arguments](http://stackoverflow.com/q/4770576) looks like it might be helpful. – jscs Aug 06 '13 at 20:39
  • I may just end up going with two separate commands as it seems clean and not as much of a hack. – jay Aug 07 '13 at 16:09

0 Answers0