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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With