Next / Previous / Contents / TCC Help System / NM Tech homepage

28.10.6. Other useful ArgumentParser methods

These methods are available on your ArgumentParser instance:

.print_usage(file=None)

Prints the short summary of argument usage. The default file is sys.stdout.

.print_help(file=None)

Prints the full summary of argument usage, including the help text for each argument. The default file is sys.stdout.

.format_usage()

Formats the short summary of argument usage and returns it as a string.

.format_help()

Formats the full help text and returns it as a string.

.exit(status=0, message=None)

Terminates execution with status 0 (or the status value you provide). If you provide a message string, that message will be printed before termination.

.error(message)

Prints the usage message, plus the message string you provide, then terminates execution with status 2.

.add_mutually_exclusive_group(required=False)

If you have two or more options that cannot be specified on the same command line, use this method to create an option group. Then call the .add_argument() on the group instance to add these options. If you specify required=True, the user is required supply one of the options in the group.

Suppose for example that you have two mutually exclusive options --english and --metric. This code would prohibit the user from specifying both at once:

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group()
g.add_argument("-e", "--english", dest="isMetric", action="store_false")
g.add_argument("-m", "--metric", dest="isMetric", action="store_true")
.set_defaults(**kw)

Use this method to specify the default values of any variable. For each keyword argument n=v, the value of n in the result returned by .parse_args() will have value v in case the user does not specify a value explicitly.

For example, if you have two mutually exclusive options, but you don't require one or the other, the .set_defaults() method is a good way to specify the value of the option when neither is given. Here is an interactive example showing this technique.

>>> parser = argparse.ArgumentParser()
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument("-y", "--yes", dest="which", action="store_true")
>>> group.add_argument("-n", "--no", dest="which", action="store_false")
>>> parser.set_defaults(which=True)
>>> print parser.parse_args(["--no"])
Namespace(which=False)
>>> print parser.parse_args(["-y"])
Namespace(which=True)
>>> print parser.parse_args([])
Namespace(which=True)