Argparse: how to distinguish arguments for parsers and subparameters

I want to use python-argparse with arguments and positional arguments. Let's say I have a script on the command line (this is just a simple and simple example), this is my code:

#!/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 as follows:

~ $ 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 tell if the verbose command is a regular parameter or a subparser parameter. But I need to process these parameters separately. What would be a simple way (with minimal code effort) to do this?

EDIT

I registered a problem inside the Python stdlib tracker: http://bugs.python.org/issue15327

+3
source share
2 answers

add_argument :

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

:

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

-, . , , .

import argparse

class _Action(object):
    def __init__(self,master):
        self.master=master
    def add_parser(self,name,**kwargs):
        self.master.subparsers[name]=subParserEnabler()
        return self.master.subparsers[name]

class subParserEnabler(argparse.ArgumentParser):
    def __init__(self,*args,**kwargs):
        self.subparsers={}
        argparse.ArgumentParser.__init__(self,*args,**kwargs)

    def add_subparsers(self,**kwargs):
        return _Action(self)

    def parse_args(self,args,**kwargs):
        args=list(args)
        for k in self.subparsers.keys():
            if k in args:
                break
        try: 
            i=args.index(k)
            output=argparse.ArgumentParser.parse_args(self,args[:i],**kwargs)
            o1=argparse.Namespace()
            setattr(output,k,o1)
            self.subparsers[k].parse_args(args[i+1:],namespace=o1)
        except:
            output=argparse.ArgumentParser.parse_args(self,args,**kwargs)
        return output

parser = subParserEnabler()
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_false')

args = parser.parse_args("--verbose command1 --verbose".split())
print args

, , , ... , , , . , , , , .

+3

All Articles