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

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 -h
usage: [--flag1 FLAG1] {group} ... 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 )
print( ‘Enter interactive loop’ )

print( init_ns )

This allows:

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

positional arguments:

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

So, we get the full help.

$ python --flag1=a
Enter interactive loop

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

$ python --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.


Leave a Reply

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

You are commenting using your 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


%d bloggers like this: