Python, accept parameters from the command line

When we call the program from the command line, Python provides several ways to handle the passed parameters.

So far, you have run programs from the REPL or using

python <filename>.py

When doing so, you can pass other parameters and options as follows:

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

The basic way to deal with these parameters is to usesysModules in the standard library.

You can pass parameters tosys.argvList:

import sys
print(len(sys.argv))
print(sys.argv)

Thissys.argvlist as the first item contains the name of the file that has been run, for example['main.py'].

This is a simple method, but you have to do a lot of work. You need to verify the parameters to ensure that they are of the correct type, and if the user does not use the program correctly, you need to print feedback to the user.

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

First you importargparseThen you callargparse.ArgumentParser(), Transfer program description:

import argparse

parser = argparse.ArgumentParser( description=‘This program prints the name of my dogs’ )

Then, you continue to add the parameters you want to accept. For example, in this procedure, we accept-cThe options for passing colors are as follows:python program.py -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 no parameters are specified, the program will throw an error:

➜  python python program.py
usage: program.py [-h] -c color
program.py: 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 program.py -c blue
usage: program.py [-h] -c color
program.py: 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: