Command Line Arguments

Example 1: Generate Help Argument and Message

Consider the code sample below:

import argparse

parser = argparse.ArgumentParser(description='A test program.')
args = parser.parse_args()
$ ./test.py -h
$ ./test.py --help

A test program.

optional arguments:
  -h, --help  show this help message and exit

Example 2: Handle a String Argument

import argparse

parser = argparse.ArgumentParser(description='A test program.')

parser.add_argument("print_string", help="Prints the supplied argument.")

args = parser.parse_args()

print(args.print_string)

To define and parse optional arguments, you can use “–” (double dash) and change their default values using the “default” argument.

You can also define shorthand versions of the argument using “-” (single dash) to reduce verbosity.

Example 3: Handle an Integer Argument

Example 4: Handle True and False Toggles

Example 5: Treat Argument Values as List

If you want to get multiple values at once and store them in list, you need to supply “nargs” keyword in following format:

Example 6: File as command line argument for argparse - error message if argument is not valid

You just need to write a function which checks if the file is valid and writes an error otherwise. Use that function with the type option. Note that you could get more fancy and create a custom action by subclassing argparse.Action, but I don't think that is necessary here. In my example, I return an open file handle (see below):

Example 7: File Extension Checking - argsparse

Example 8: Require either of two arguments using argparse

If you need some check that is not provided by the module you can always do it manually:

Example 8: If arg is A, do this, if B do that, if none of the above show help and quit

adding to it:

Or try the following:

Here's the way I do it with argparse (with multiple args):

args will be a dictionary containing the arguments:

Last updated

Was this helpful?