Tutorial by Examples

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', ...
docopt turns command-line argument parsing on its head. Instead of parsing the arguments, you just write the usage string for your program, and docopt parses the usage string and uses it to extract the command line arguments. """ Usage: script_name.py [-a] [-b] <path> ...
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...
Whenever a Python script is invoked from the command line, the user may supply additional command line arguments which will be passed on to the script. These arguments will be available to the programmer from the system variable sys.argv ("argv" is a traditional name used in most programmi...
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 ...
As with docopt, with [docopt_dispatch] you craft your --help in the __doc__ variable of your entry-point module. There, you call dispatch with the doc string as argument, so it can run the parser over it. That being done, instead of handling manually the arguments (which usually ends up in a high c...

Page 1 of 1