Posted by: Mike P. | April 3, 2015

Python argparse and option subparsers


So, now I am moving a different space – Python programming.

A common issue that seems to crop up is how to make use of the argparse module
but have the program continue if no subcommands are present in the argument
list.

The most common case is:


import argparse

p1 = argparse.ArgumentParser( add_help = False )
p1.add_argument( ‘–flag1’ )

s = p1.add_subparsers()
p = s.add_parser( ‘group’ )
p.set_defaults( group=True )

ns = p1.parse_args()

print( ns )

And it prints:


$ python b.py -h
usage: b.py [--flag1 FLAG1] {group} ...
b.py: error: too few arguments

So, my solution uses two argument parse objects, and a parent linkage as follows:


import argparse
import sys

p1 = argparse.ArgumentParser( add_help = False )
p1.add_argument( ‘–flag1’ )

p2 = argparse.ArgumentParser( parents = [ p1 ] )
s = p2.add_subparsers()
p = s.add_parser( ‘group’ )
p.set_defaults( group=True )

( init_ns, remaining ) = p1.parse_known_args( )

if remaining:
p2.parse_args( args = remaining, namespace=init_ns )
else:
print( ‘Enter interactive loop’ )

print( init_ns )

This allows:


$ python a.py -h
usage: a.py [-h] [--flag1 FLAG1] {group} ...

positional arguments:
{group}

optional arguments:
-h, –help show this help message and exit
–flag1 FLAG1

So, we get the full help.


$ python a.py --flag1=a
Enter interactive loop
Namespace(flag1='a')

So, no sub-command so we enter the interactive loop, but the flag was seen. And finally:


$ python a.py --flag1=a group
Namespace(flag1='a', group=True)
$

A subcommand was found and processed, and the program exited.

Neat! Lots of questions on this in various places.  Please excuse the lack of indents in the code.  There are only two such lines.  I need to fix this blog so it prints code properly.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: