4

I have a program which can be used in the following way:

program install -a arg -b arg program list program update 

There can only ever be one of the positional arguments specified (install, list or update). And there can only be other arguments in the install scenario.

The argparse documentation is a little dense and I'm having a hard time figuring out how to do this correctly. What should my add_arguments look like?

5
  • 1
    Did you look through the argparse tutorial instead? Commented May 20, 2013 at 1:59
  • @JonathonReinhart, no I didn't thanks for the link. I'll see what I can get from it. Commented May 20, 2013 at 1:59
  • 1
    @TankyWoo, read the last paragraph of my question. Also, having this information on SO makes it easier for other people looking for the same information. If RTFM was a blanket rule, SO wouldn't exist. Commented May 20, 2013 at 2:11
  • 1
    I agree with MaxMackie here. The argparse documentation is something I struggle with nearly every time I go to do something non-trivial with it. Commented May 20, 2013 at 2:13
  • @MaxMackie yes, the manual is very dense, but the argparse doc is very good, and if you want to master the commandline in python. I think you need to read it. Recently I write some nagios plugins in python, and the argparse is very important. So I have read the doc some times, it was really very good. Commented May 20, 2013 at 2:22

1 Answer 1

9

This seems like you want to use subparsers.

from argparse import ArgumentParser parser = ArgumentParser() subparsers = parser.add_subparsers() install = subparsers.add_parser('install') install.add_argument('-b') install.add_argument('-a') install.set_defaults(subparser='install') lst = subparsers.add_parser('list') lst.set_defaults(subparser='list') update = subparsers.add_parser('update') update.set_defaults(subparser='update') print parser.parse_args() 

As stated in the docs, I have combined with set_defaults so that you can know which subparser was invoked.

Sign up to request clarification or add additional context in comments.

6 Comments

This looks nice and easy. I'll give it a try before accepting.
Works just like I need it to, however, in this situation, I have no way or knowing if list or update has been called seeing as they both return an empty dictionary. If there a built in way for me to distinguish between the two?
@MaxMackie -- That's there the set_default comes in.
Saw that, thanks for the example. argparse is so clean when you know how to use it :)
@n0pe [and mgilson] use subparsers = parser.add_subparsers(dest="cmd") instead of set_default.
|