Python

sys.argv() in Python

The sys module consists of functions and variables that strongly interact with the interpreter. The sys module comes pre-loaded in Python and does not require any installation. Amongst the many functions and variables are sys.argv(). Sys.argv() is used to gather command line user input. In this tutorial, we will be learning about sys.argv(), and its common uses.

sys.argv

In essence, Sys.argv() is a list of all the command line inputs. When the script is executed, you can feed its user input in various ways, and one such way is via the command line. In this first instance, let us suppose that we have a simple script called main.py.

print(“hello world”)

While executing the script, we’re going to add a few command line arguments in addition to the script name. If we were to execute the script, we would get the following:

$ python3 main.py what are you up to?
hello world

You notice here that the command line arguments did not interfere with the script itself.

So, now, let’s modify the script a little bit. So, suppose that now we have a script called main.py with the following content:

import sys

print(sys.argv)

If we were to execute the script, we would get the following:

$ python3 main.py
[‘main.py’]

As you can see, we get a list with one item in it because we only supplied it with one item, the script name. Now suppose that we supply it a slightly different command line input arguments.

import sys
print(sys.argv)

If we were to execute the script, we would get the following:

$ python3 main.py hello world
[‘main.py,’ ‘hello,’ ‘world’]

Now, what happens is that it retrieves everything we provided via the command line or all the command line arguments provided by the user. In my case, I added ‘hello world’ after the name of the script, and as such, it retrieved it to the list.

sys.argv[0]

Sys.argv[0] is the first argument in the list. In all cases, the first argument is always the name of the script.

import sys
name_of_script = sys.argv[0]
print(name_of_script)

When executing the script, we would type the following:

$ python3 main.py
main.py

sys.argv[n]

Alternatively, you may wish to retrieve a specific command line argument. For example, you may wish to retrieve the user’s input via command line arguments when writing a Python program. In this scenario, we’ll retrieve the first three command line arguments.

import sys

name1 = sys.argv[1]
name2 = sys.argv[2]
name3 = sys.argv[3]

print("hello",  name1,,,name2,and,name3)

When executing the script, we would type the following for example:

$ python3 main.py Trevor Travis Tim
hello Trevor, Travis, and Tim

Here, sys.argv[1] is the second command line argument, while sys.argv[2] is the third command line argument, and sys.argv[3] is the fourth command line argument. This is so because although the index begins at 0, and sys.argv[0] is the name of the script.

So what if the user was expected to enter n number of inputs and we didn’t know how many inputs there were? Suppose the following script was written:

import sys

list = sys.argv[1:]

for value in list:
    print(value)

When executing the script, we would type the following for example:

$ python3 main.py hello Trevor Travis and Tim
hello
Trevor
Travis
and
Tim

Here, sys.argv[1:] means that all values from sys.argv[1] are used until the end of the list. In this case, we can add as many command line arguments as we want.

Strings

Please note that all values captured by the variable sys.argv are strings. So suppose that we wanted to add three numbers that the user inputs.

import sys

num1 = sys.argv[1]
num2 = sys.argv[2]
num3 = sys.argv[3]

list = [num1, num2, num3]
total = sum(list)
print(total)

If we were to execute the script, we would get the following:

$ python3 main2.py 3 4 5
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

What we get is a TypeError. This is because all of the values obtained from the list are “string” values while we require integer values to add. In order to correct this, we would have to convert the strings to integers:

import sys

num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
num3 = int(sys.argv[3])

list = [num1, num2, num3]
total = sum(list)
print(total)

If we were to execute the script, we would get the following:

$ python3 main2.py 3 4 5
12

We added int(sys.arg[n]) ensured that we converted the string to an integer.

Sys.argv errors

One of the most common errors that are thrown (when we don’t use sys.argv[1:] but rather specify the nth value using sys.argv[n]) is that of an IndexError (list index out of range). What this error means is that the command line arguments were not specified, and in order to avert this error, we must take a few precautionary steps:

import sys

if len(sys.argv)  4:
    print("please enter three names")

if len(sys.arv) == 4:
    name1 = sys.argv[1]
    name2 = sys.argv[2]
    ame3 = sys.argv[3]

print("hello", name1)
print("hello", name2)
print("hello", name3)

When executing the script, we would type the following for example:

$ python3 main.py Travis Trevor Tim
hello Travis
hello Trevor
hello Tim

In order to avert the error, we must adjust the length of the command line arguments. In the previous example, we have three names and a script name, which means that there are a total of 4 values. Thus, we say that if the length is greater than 4 or less than 4, then ask the user to input three names; else, print out the three names.

The sys module is very important as it allows interaction with the Python interpreter. In particular, the variable sys.argv is a list that contains all of the users’ inputted command line arguments. Sys.argv[0] defines the name of the script in all cases. Although sys.argv() is very commonly utilized to gather command line arguments, another even better way of gathering command line arguments is by using argparse. But that’s a story for another day!

About the author

Kalyani Rajalingham

I'm a linux and code lover.