Display help message with python argparse when script is called without any arguments Display help message with python argparse when script is called without any arguments python python

Display help message with python argparse when script is called without any arguments


This answer comes from Steven Bethard on Google groups. I'm reposting it here to make it easier for people without a Google account to access.

You can override the default behavior of the error method:

import argparseimport sysclass MyParser(argparse.ArgumentParser):    def error(self, message):        sys.stderr.write('error: %s\n' % message)        self.print_help()        sys.exit(2)parser = MyParser()parser.add_argument('foo', nargs='+')args = parser.parse_args()

Note that the above solution will print the help message whenever the errormethod is triggered. For example, test.py --blah will print the help messagetoo if --blah isn't a valid option.

If you want to print the help message only if no arguments are supplied on thecommand line, then perhaps this is still the easiest way:

import argparseimport sysparser=argparse.ArgumentParser()parser.add_argument('foo', nargs='+')if len(sys.argv)==1:    parser.print_help(sys.stderr)    sys.exit(1)args=parser.parse_args()

Note that parser.print_help() prints to stdout by default. As init_js suggests, use parser.print_help(sys.stderr) to print to stderr.


Instead of writing a class, a try/except can be used instead

try:    options = parser.parse_args()except:    parser.print_help()    sys.exit(0)

The upside is that the workflow is clearer and you don't need a stub class. The downside is that the first 'usage' line is printed twice.

This will need at least one mandatory argument. With no mandatory arguments, providing zero args on the commandline is valid.


With argparse you could do:

parser.argparse.ArgumentParser()#parser.add_args here#sys.argv includes a list of elements starting with the programif len(sys.argv) < 2:    parser.print_usage()    sys.exit(1)