In a previous blog post we discussed accepting user input. Building on this post, we are going to discuss how to deal with arguments when running a Python program. When running a program in Python, we type the following at the command line: python nameOfFile.py. When we want to add arguments we do it in the following manner: python nameOfFile.py arg1 arg2. But how do we accept these arguments in our Python program?

Accepting arguments

In order to accept these arguments in our Python program, we can use sys from Python’s standard library:

import sys
print(sys.argv)

sys.argv is a list that contains as the first element the name of the file that we are running (i.e. [nameOfFile.py]).

Parsing arguments

We can use another module called argparse from the standard library to add a description of a program and to validate arguments inputted by the user as follows:

import argparse

parse = argparse.ArgumentParser(
    description='This program does the following....'
)

parse.add_argument('-n', '--name')

arg = parse.parse_args()

print(arg.name)

If we run a program python names.py -n Tom, it will output Tom. If we don’t pass an argument, we will get an error:

names.py: error: the following arguments are required: -n name