How To Use sys.arv in Python

Students new to Python learn early on how to use input() to accept data from users. There is, however, another method of interacting with a program.

With the sys module, it’s possible to pass arguments to a Python program directly from the command prompt, or terminal.

This feature allows for greater flexibility when writing and running programs. For instance, by providing different arguments to a Python program, it’s possible to change the behavior of the code.

We can tell Python programs to perform different functions depending on what arguments are passed via the command line.

What is sys.argv?

The sys module lets us affect the behavior of the Python interpreter. With sys.argv, Python will look for arguments in the command line and supply them as a list to our program.

This means we can look for input provided by the user when they run the program. We can then use that info to change the output.

How do I use it?

Before you can use the sys module, you’ll need to import it. We can do this with the import keyword, followed by the name of the module.

Import syntax:

import module_name

There are plenty of Python libraries to choose from. It’s a good idea to familiarize yourself with common modules like sys.

Example 1: Importing the sys module

import sys

print(sys.version)

Running this code will tell you the version of Python you’re using, as well as some other pertinent information about your computer system.

With the sys module we can manipulate the Python runtime environment. For instance, we can change the way we interact with the Python from the command line.

Introducing Command Line Arguments

The sys module lets us provide python with additional arguments from the command line. These arguments are included as a list. They can be used to change the way a program behaves from the command line.

These additional arguments come after the name of your python file. Here’s the syntax for using command line arguments in Python:

python python_file.py arg1 arg2 arg3

In the following example, we’ll pass three arguments. Using the len() method, we can find and display the length of the sys.argv list.

Example 2: Using sys.argv

# use len() to find the number of arguments passed to Python
import sys
total_args = len(sys.argv)

print("You passed: {} arguments.".format(total_args))
print("First argument: {}".format(sys.argv[0]))

In the command prompt, after you type “python” and the name of your file, include some additional arguments, like so:

Input

python pfb_args.py one two three

Output

You passed: 4 arguments.
First argument: argv.py

As you can see, Python includes the name of the file as the first argument. Additional arguments follow in the order they were given.

By default, the len() method includes the file name in the list of arguments. If we want to know the number of arguments passed and not include the file name, we can use len(sys.argv)-1.

import sys
# exclude the file name from the list of arguments
total_args = len(sys.argv)-1

print("You passed: {} arguments.".format(total_args))

Input

python pfb_args.py one two

Output

You passed: 2 arguments.

Print all the elements in sys.argv

Because the command line arguments are passed as a list, we can iterate through them with a for loop.

Example 3: Printing sys.argv with a for loop

import sys

total_args = len(sys.argv)

for i in range(total_args):
    print("First argument: {}".format(sys.argv[i]))

Input

python pfb_args.py one two three

Output

First argument: argv.py
First argument: one
First argument: two
First argument: three

Printing sys.argv with the str() method

There is, however, an easier way to print the contents of sys.argv. The str() method lets us print the contents of sys.argv as a string.

Example 5: Using the str() method with sys.argv

import sys
print(str(sys.argv))

In the command prompt:

python pfb_args.py one two three

Output

['argv.py', 'one', 'two', 'three']

Find the powers of a number with sys.argv

We can use command line arguments to find the powers of a number from the terminal.

Before we can perform any calculations on the input, we’ll need to convert the arguments. By default, Python assumes that we are passing strings.

To convert strings to numbers, use the int() method. In the following example, the int() method is used to convert the user input into numbers.

In Python, the ** operator is used to find the powers of a given number.

Example 6: Finding powers

number = int(sys.argv[1])
power = int(sys.argv[2])

print("{} to the power of {} is {}.".format(number, power, number**power))

Input

python pfb_args.py 9 2

Output

9 to the power of 2 is 81.

Find the average of a set

In another example, we can use sys.argv to find the average of a set of numbers. We’ll use a python string split method to remove the first element from the list. Remember, the first element in the sys.argv list will be the name of the python file. We want to ignore this.

Any arguments passed to Python from the command line will be read as strings. We have to use float() to convert them to a floating point number.

After obtaining the sum, we’ll need to divide it by the length of the set. One way to find how many numbers were passed is to subtract 1 from the length of sys.argv.

Example 7: Using sys.argv to find the average of a set of numbers

# find the average of a set of numbers 
import sys

nums = sys.argv[1:]
sum = 0

for num in nums:
    sum += float(num)

average = sum/(len(sys.argv)-1)

print("The average of the set is: {}".format(average))

Input

python sum_of_set.py 5 100 14 25

Output

The average of the set is: 36.0

Reading a file with sys.argv

The sys module is commonly used for working with multiple files. For example, if we wrote a Python program to edit text files, it would be useful if there was a way to easily tell the program what files to read.

With the information we’ve learned about the sys module and command line arguments, we can tell Python to read text files. Furthermore, we can provide several files at once, and Python will read them all.

In the next example, we’ll read multiple files using sys.argv. I’ve created two files on my computer. Each contains a few lines from Act II of Shakespeare’s Hamlet.

Here are the text files. Save them in the same folder as your Python file:

hamlet_part1.txt

KING CLAUDIUS
How is it that the clouds still hang on you?
HAMLET
Not so, my lord; I am too much i’ the sun.

hamlet_part2.txt

QUEEN GERTRUDE
Good Hamlet, cast thy nighted colour off,
And let thine eye look like a friend on Denmark.
Do not for ever with thy vailed lids
Seek for thy noble father in the dust:
Thou know’st ’tis common; all that lives must die,
Passing through nature to eternity.
HAMLET
Ay, madam, it is common.

Using sys.argv, we’ll tell Python to open each file and print its contents to the console. We’ll also make use of the readline() method to read the lines of the text files.

Example 8: Reading multiple files with the sys module

import sys
# read files with sys.argv

def read_file(filename):
    with open(filename) as file:
        while True:
            line = file.readline()

            if len(line) == 0:
                break

            print(line)

files = sys.argv[1:]

for filename in files:
    read_file(filename)

Once the program has the file names, provided by sys.argv, a for loop is used to open each file. In the terminal, we’ll supply Python with the names of the files.

Input

python sys_read_file.py hamlet_part1.txt hamlet_part2.txt

Output

KING CLAUDIUS
How is it that the clouds still hang on you?
HAMLET
Not so, my lord; I am too much i' the sun.
QUEEN GERTRUDE
Good Hamlet, cast thy nighted colour off,
And let thine eye look like a friend on Denmark.
Do not for ever with thy vailed lids
Seek for thy noble father in the dust:
Thou know'st 'tis common; all that lives must die,
Passing through nature to eternity.
HAMLET
Ay, madam, it is common.

Leave a Reply

Your email address will not be published. Required fields are marked *