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

28.10.6. Other useful ArgumentParser methods

These methods are available on your ArgumentParser instance:


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


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


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


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.


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


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")

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"])
>>> print parser.parse_args(["-y"])
>>> print parser.parse_args([])