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 When we want to add arguments we do it in the following manner: python 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

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

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()


If we run a program python -n Tom, it will output Tom. If we don’t pass an argument, we will get an error: error: the following arguments are required: -n name