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.
Sometimes, we may want to pass arguments to our Python script while executing it from the command line. In such cases,
sys.argv comes handy.
sys.argv available in the
sys module is a list object that stores command-line arguments passed to a Python script as strings.
The arguments that we pass from the command line get stored in the
sys.argv list as strings provided that the name of the file occupies the first place.
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?
sys.argv, we first have to import the
sys module in our Python program.
Then, using the indexing operator
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 number, all arguments are stores as string in
#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'>
sys.argv is a simple Python list object available in the
sys module that stores the command line arguments as strings.