This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

sys.argv

Let’s say we want to build our calculator program in Python. For simplicity, we require the user to input three items as command line arguments:

  • first number
  • second number
  • an operation (add, sub, mul, div)

So the user will execute the program like this

$ python3 calculator.py 3 5 add
8

You can use the sys.argv variable to retrieve the list of command line arguments (including the script name) enetered by the user.

The content of calculator.py will be as follows:

import sys

print(sys.argv)
print(len(sys.argv))
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
print(sys.argv[3])

And when you run calculator.py with some input arguments:

$ python3 calculator.py 6 2 add
['calculator.py', '6', '2', 'add']
4
calculator.py
6
2
add

As you can see, sys.argv gives you the list of command line arguments, with the first element being the name of your script, and the remaining elements being whatever were entered by the user.

We could then just use these values to perform our calculations in calculator.py:

import sys

def calculate(x, y, operation):
    if operation == "add":
        return x + y
    elif operation == "sub":
        return x - y
    elif operation == "mul":
        return x * y
    elif operation == "div":
        return x / y

x = int(sys.argv[1])
y = int(sys.argv[2])
operation = sys.argv[3]
print(calculate(x, y, operation))

You can then run your calculator program.

$ python3 calculator.py 4 7 mul
28