Tutorial by Examples: argparse

The following program says hello to the user. It takes one positional argument, the name of the user, and can also be told the greeting. import argparse parser = argparse.ArgumentParser() parser.add_argument('name', help='name of user' ) parser.add_argument('-g', '--greeting', ...
If you want two or more arguments to be mutually exclusive. You can use the function argparse.ArgumentParser.add_mutually_exclusive_group(). In the example below, either foo or bar can exist but not both at the same time. import argparse parser = argparse.ArgumentParser() group = parser.add_mut...
You can create parser error messages according to your script needs. This is through the argparse.ArgumentParser.error function. The below example shows the script printing a usage and an error message to stderr when --foo is given but not --bar. import argparse parser = argparse.ArgumentParser...
When you create an argparse ArgumentParser() and run your program with '-h' you get an automated usage message explaining what arguments you can run your software with. By default, positional arguments and conditional arguments are separated into two categories, for example, here is a small script ...
import argparse import sys def check(): print("status") return 0 parser = argparse.ArgumentParser(prog="sub", add_help=False) subparser = parser.add_subparsers(dest="cmd") subparser.add_parser('status', help='show status') subparser.add_parser('lis...
Extended version of http://www.riptutorial.com/python/example/25282/argparse--default-help-formatter- that fixed help output. import argparse import sys class CustomHelpFormatter(argparse.HelpFormatter): def _format_action(self, action): if type(action) == argparse._SubParsersActi...

Page 1 of 1