Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse: how to distinguish between arguments for parsers and subparsers

I want to use python-argparse with arguments and positional arguments. Say I have my script on a commandline (which is just a simple&stupid example), this is my code so far:

#!/usr/bin/env python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--verbose', action='store_true')
subparsers = parser.add_subparsers(help='command', dest='command')
cmd1_parser = subparsers.add_parser('command1')
cmd1_parser.add_argument('--verbose', action='store_true')

args = parser.parse_args()

print args

Now I call this script like this:

~ $ myscript --verbose command1 --verbose
Namespace(command='command1', verbose=True)

~ $ myscript command1 --verbose
Namespace(command='command1', verbose=True)

~ $ myscript --verbose command1
Namespace(command='command1', verbose=True)

Now as you can see I always get the same Namespace-object, and cannot distinguish if the verbose command is a regular parameter or a subparser parameter. But I need that to handle these parameters separately. What would be an easy way (with minimum code efforts) to do that?

EDIT:

I filed an issue inside the Python stdlib issue tracker: http://bugs.python.org/issue15327

like image 586
Wolkenarchitekt Avatar asked Jan 17 '23 22:01

Wolkenarchitekt


1 Answers

Change your subparser's add_argument call to this:

cmd1_parser.add_argument('--verbose', action='store_true', dest='cmd1_verbose')

This will result in your first example returning:

~ $ myscript --verbose command1 --verbose
Namespace(cmd1_verbose=True, command='command1', verbose=True)
like image 189
John Gaines Jr. Avatar answered Feb 01 '23 16:02

John Gaines Jr.