Passing arguments to your Python script

Since I am so used to PowerShell, my first thought when I wanted to call a python script was to do something like “script -argument”. Of course, Python offers this functionality too. With the help of sys.argv you have a very simple way to enable parameters for your Python script.

Using Sys.argv

The argv attribute of the sys (sys.argv)module offers a way to pass command line arguments to a Python script. It creates a list, and the arguments can be called using argv[n] where n is the position of the parameter in the command line. argv[0] would be the name of the script, argv[1] the first argument after the name of the script, argv[2] the second one and so on. This behavior can be seen if we print sys.argv:

#!/usr/bin/env python3
import sys

print(sys.argv)

for i in sys.argv:
    print(i)

Call and output:

$ ./arguments.py Argument1 Argument2 Argument3 Argument...
['./arguments.py', 'Argument1', 'Argument2', 'Argument3', 'Argument...']
./arguments.py
Argument1
Argument2
Argument3
Argument...

An optional way to call just the argv attribute from sys is using the from keyword:

#!/usr/bin/env python3
from sys import argv

print(argv)

for i in argv:
    print(i)

Sys.argv captures strings

All the arguments that sys.argv reads from the command line are captured as strings. If you want to perform operations with numbers (or another type of data different than strings), you will have to convert the data and ignore the first position that corresponds to the script name:

#!/usr/bin/env python3
from sys import argv

numbers = [int(i) for i in argv[1:]]
print(sum(numbers))

Making parameters required

To specify that the script needs a specific amount of parameters, we can check the length of sys.argv:

#!/usr/bin/env python3
from sys import argv

if len(argv) != 3:
    print("Usage: all 3 parameters are required")
    exit(1)

If we call the script with a number of parameters different than 3, we will see the error message:

$ ./arguments.py 1 2 3
Usage: all 3 parameters are required

Check if the parameters are numbers

If you want to check if the script was called with only numbers (or any other type of data), you can use a try to see if the conversion to a specific type of data fails or not:

#!/usr/bin/env python3
from sys import argv

try:
    [int(i) for i in argv[1:]]
except ValueError:
    print("Please enter only numbers")
    exit(1)

The output of that code looks like this when the script is called with parameters that are not numbers:

$ ./arguments.py 1 2 4 5 test
Please enter only numbers

Those are the basics of using parameters with Python. In the future, we will be reviewing the argparse module which offers a lot of cool features when it comes to using parameters with Python scripts.

| Theme: UPortfolio