argparse with required subcommands

PonyEars picture PonyEars · Aug 16, 2013 · Viewed 12.3k times · Source

With python's argparse, how do I make a subcommand a required argument? I want to do this because I want argparse to error out if a subcommand is not specified. I override the error method to print help instead. I have 3-deep nested subcommands, so it's not a matter of simply handling zero arguments at the top level.

In the following example, if this is called like so, I get:

$./simple.py
$

What I want it to do instead is for argparse to complain that the required subcommand was not specified:

import argparse

class MyArgumentParser(argparse.ArgumentParser):
    def error(self, message):
        self.print_help(sys.stderr)
        self.exit(0, '%s: error: %s\n' % (self.prog, message))

def main():
    parser = MyArgumentParser(description='Simple example')
    subs = parser.add_subparsers()
    sub_one = subs.add_parser('one', help='does something')
    sub_two = subs.add_parser('two', help='does something else')

    parser.parse_args()

if __name__ == '__main__':
    main()

Answer

hpaulj picture hpaulj · Aug 17, 2013

There was a change in 3.3 in the error message for required arguments, and subcommands got lost in the dust.

http://bugs.python.org/issue9253#msg186387

There I suggest this work around, setting the required attribute after the subparsers is defined.

parser = ArgumentParser(prog='test')
subparsers = parser.add_subparsers()
subparsers.required = True
subparsers.dest = 'command'
subparser = subparsers.add_parser("foo", help="run foo")
parser.parse_args()

update

A related pull-request: https://github.com/python/cpython/pull/3027