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, thus in some cases, 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 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.

Post author avatar

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply