What is sys.argv in Python?

Python Tutorials

Summary: In this tutorial, we will learn what is sys.argv in Python, what are its significances and how can we use it in our Python program.

Most of the time we execute Python scripts directly from the command line. But sometimes, we may also need to pass arguments to those scripts directly from the command line.

In such cases, sys.argv comes handy.

The sys.argv is a list object which is available in the Python’s sys module. It stores all the command-line arguments passed to a Python script as string objects.

The arguments that we pass from the command line are stored as strings in the sys.argv list, provided the name of the file occupies the first place.

Example:

Consider, that we have a python script named myscript.py and we want to pass four different arguments to it.

In that case, we would run the command as follows and the sys.argv list will have those arguments stored in it.

>>> Python myscript.py arg1 arg2 arg3 arg4

How to use sys.argv?

To use sys.argv, we first have to import the sys module in our Python program.

Then, using the indexing operator [] on sys.argv, we can access the command-line arguments.

Tip: Always check the number of arguments passed using len(sys.argv) before accessing them in the program.

#myscript.py
import sys

count = len(sys.argv)
print("Number of arguments:", count)

for arg in sys.argv:
    print(arg)

Run the script:

>>> Python myscript.py one two three four
Number of arguments: 5
myscript.py
one
two
three
four

As you can see, the name of the file is stored in the 0th index of the list followed by the arguments in the same order as they were passed on the command line.

However, it is important to note that sys.argv doesn’t preserve the type of arguments.

Whether we pass integer or floating numbers, all arguments are stores as strings in the sys.argv list.

#myscript.py
import sys

count = len(sys.argv)
print("Number of arguments:", count)

for arg in sys.argv:
    print(type(arg))

Run the script to know the types of each argument:

>>> Python myscript.py one two 3 4
Number of arguments: 5
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

In conclusion, sys.argv is a simple Python list object available in the sys module that stores the command line arguments as strings.

Leave a Reply

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