What are command line arguments in python?

In the command line, we can start a program with additional arguments.
These arguments are passed into the program.

Python programs can start with command line arguments. For example:

$ python program.py image.bmp

where program.py and image.bmp is are arguments. (the program is Python)

Related Course:
Complete Python Programming Course & Exercises

How to use command line arguments in python?

We can use modules to get arguments.

Which modules can get command line arguments?

Module Use Python version
sys All arguments in sys.argv (basic) All
argparse Build a command line interface >= 2.3
docopt Create command line interfaces >= 2.5
fire Automatically generating command line interfaces (CLIs) All
optparse Deprecated < 2.7

Sys argv

You can get access to the command line parameters using the sys module. len(sys.argv) contains the number of arguments. To print all of the arguments simply execute str(sys.argv)

#!/usr/bin/python

import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))

Example:

python command line arguments

python sys argv example

You can store the arguments given at the start of the program in variables.
For example, an image loader program may start like this:

#!/usr/bin/python

import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))

if sys.argv < 2:
print('To few arguments, please specify a filename')

filename = sys.argv[1]
print('Filename:', filename)

Another example:

(‘Arguments:’, 2)
(‘List:’, “[‘example.py’, ‘world.png’]”)
(‘Filename:’, ‘world.png’)

Related Course: Complete Python Programming Course & Exercises

Argparse

If you need more advanced parsing, you can use argparse.
You can define arguments like (-o, -s).

The example below parses parameters:

  
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-o','--open-file', help='Description', required=False)
parser.add_argument('-s','--save-file', help='Description', required=False)

args = parser.parse_args()

print(args.open_file)
print(args.save_file)

Docopt

Docopt can be used to create command line interfaces.

  
from docopt import docopt

if __name__ == '__main__':
arguments = docopt(__doc__, version='Example 1.0')
print(arguments)

**Note:** docopt is not tested with Python 3.6

Fire

Python Fire automatically generates a command line interface, you only need one line of code. Unlike the other modules, this works instantly.

You don’t need to define any arguments, all methods are linked by default.

To install it type:

pip install fire

Then define or use a class:
  
import fire

class Program(object):
def hello(self):
print("Hello World")

def openfile(self, filename):
print("Opening file '" + filename + "'")

if __name__ == '__main__':
fire.Fire(Program)

You then have the options matching the class methods:
python example.py hello
python example.py openfile filename.txt


Download exercises