Verbose level with argparse and multiple -v options

Charles Brunet picture Charles Brunet · May 20, 2011 · Viewed 16.8k times · Source

I'd like to be able to specify different verbose level, by adding more -v options to the command line. For example:

$ myprogram.py    
$ myprogram.py -v
$ myprogram.py -vv
$ myprogram.py -v -v -v

would lead to verbose=0, verbose=1, verbose=2, and verbose=3 respectively. How can I achieve that using argparse?

Optionally, it could be great to also be able to specify it like

$ myprogram -v 2

Answer

Ben picture Ben · Dec 1, 2011

argparse supports action='count':

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', action='count', default=0)

for c in ['', '-v', '-v -v', '-vv', '-vv -v', '-v -v --verbose -vvvv']:
    print(parser.parse_args(c.split()))

Output:

Namespace(verbose=0)
Namespace(verbose=1)
Namespace(verbose=2)
Namespace(verbose=2)
Namespace(verbose=3)
Namespace(verbose=7)

The only very minor niggle is you have to explicitly set default=0 if you want no -v arguments to give you a verbosity level of 0 rather than None.