Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python argparse: How can I display help automatically on error?

Currently when I enter invalid options or omit positional arguments, argparse kicks me back to the prompt and displays the usage for my app. This is ok, but I would rather automatically display the full help listing (that explains the options, etc) than require the user to type

./myscript.py -h

Thanks!

Jamie

like image 639
jpswain.w Avatar asked Sep 03 '10 14:09

jpswain.w


People also ask

Which module is used for parsing command line arguments automatically in Python?

Python argparse module is the preferred way to parse command line arguments. It provides a lot of option such as positional arguments, default value for arguments, help message, specifying data type of argument etc.

What does Nargs do in Argparse?

Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.


1 Answers

To print help you might want to use: print_help function on ArgumentParser instance

parser = argparse.ArgumentParser() (...) parser.print_help() 

To print help message on error you need to create own subclass of ArgumentParser instance, that overrides error() method. For example like that:

class MyParser(argparse.ArgumentParser):     def error(self, message):       sys.stderr.write('error: %s\n' % message)       self.print_help()       sys.exit(2) 

When this parser encounters unparseable argument line it will print help.

like image 84
jb. Avatar answered Oct 14 '22 03:10

jb.