Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse optional subparser (for --version)

Tags:

I have the following code (using Python 2.7):

# shared command line options, like --version or --verbose
parser_shared = argparse.ArgumentParser(add_help=False)
parser_shared.add_argument('--version', action='store_true')

# the main parser, inherits from `parser_shared`
parser = argparse.ArgumentParser(description='main', parents=[parser_shared])

# several subcommands, which can't inherit from the main parser, since
# it would expect subcommands ad infinitum
subparsers = parser.add_subparsers('db', parents=[parser_shared])

...

args = parser.parse_args()

Now I would like to be able to call this program e.g. with the --version appended to the normal program or some subcommand:

$ prog --version
0.1

$ prog db --version
0.1

Basically, I need to declare optional subparsers. I'm aware that this isn't really supported, but are there any workarounds or alternatives?

Edit: The error message I am getting:

$ prog db --version
# works fine

$ prog --version
usage: ....
prog: error: too few arguments
like image 502
miku Avatar asked Dec 15 '11 14:12

miku


People also ask

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do I make Argparse argument optional in Python?

Python argparse optional argument The example adds one argument having two options: a short -o and a long --ouput . These are optional arguments. The module is imported. An argument is added with add_argument .

How do you make an argument mandatory in Python?

If a user is required to make an argument, they can set the keyword argument required to True .

What type does parse_args return?

Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.


2 Answers

According to documentation, --version with action='version' (and not with action='store_true') prints automatically the version number:

parser.add_argument('--version', action='version', version='%(prog)s 2.0')
like image 134
eumiro Avatar answered Sep 17 '22 18:09

eumiro


FWIW, I ran into this also, and ended up "solving" it by not using subparsers (I already had my own system for printing help, so didn't lose anything there).

Instead, I do this:

parser.add_argument("command", nargs="?",
                    help="name of command to execute")

args, subcommand_args = parser.parse_known_args()

...and then the subcommand creates its own parser (similar to a subparser) which operates only on subcommand_args.

like image 22
Matthew Avatar answered Sep 18 '22 18:09

Matthew