Python offers several ways to handle arguments passed when we invoke the program from the command line.

So far you’ve run programs either from a REPL, or using

python <filename>.py

You can pass additional arguments and options when you do so, like this:

python <filename>.py <argument1>
python <filename>.py <argument1> <argument2>

A basic way to handle those arguments is to use the sys module from the standard library.

You can get the arguments passed in the sys.argv list:

import sys

The sys.argv list contains as the first item the name of the file that was ran, e.g. [''].

This is a simple way, but you have to do a lot of work. You need to validate arguments, make sure their type is correct, you need to print feedback to the user if they are not using the program correctly.

Python provides another package in the standard library to help you: argparse.

First you import argparse and you call argparse.ArgumentParser(), passing the description of your program:

import argparse

parser = argparse.ArgumentParser(
    description='This program prints the name of my dogs'

Then you proceed to add arguments you want to accept. For example in this program we accept a -c option to pass a color, like this: python -c red

import argparse

parser = argparse.ArgumentParser(
    description='This program prints a color HEX value'

parser.add_argument('-c', '--color', metavar='color', required=True, help='the color to search for')

args = parser.parse_args()

print(args.color) # 'red'

If the argument is not specified, the program raises an error:

➜  python python
usage: [-h] -c color error: the following arguments are required: -c

You can set an option to have a specific set of values, using choices:

parser.add_argument('-c', '--color', metavar='color', required=True, choices={'red','yellow'}, help='the color to search for')
➜  python python -c blue
usage: [-h] -c color error: argument -c/--color: invalid choice: 'blue' (choose from 'yellow', 'red')

There are more options, but those are the basics.

And there are community packages that provide this functionality, too, like Click and Python Prompt Toolkit.

More python tutorials: