Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

argparse with required subcommands

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*

Draft saved
Draft discarded
Cancel
4
  • 7
    It isn't supported by the add_subparsers() method: TypeError: __init__() got an unexpected keyword argument 'required' Commented Aug 16, 2013 at 21:37
  • 3
    We are adding this to Python 3.7, and making it the default behaviour. Better late than never ¯\_(ツ)_/¯ Commented Sep 20, 2017 at 17:33
  • 2
    Did this make it into Python 3.7? It seems to be mentioned in the docs however when I use it with 3.7.1 I get a TypeError: sequence item 0: expected str instance, NoneType found so maybe not. Commented Nov 29, 2018 at 4:40
  • 2
    Turns out you also need to provide a dest so that the subparser selection has a name: parser.add_subparsers(dest="command", required=True). Commented Nov 29, 2018 at 4:47

lang-py

AltStyle によって変換されたページ (->オリジナル) /