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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With