Python provides us with different ways to perform programming. In this article, we will discuss the sys.argv list in python and its use with an example.
What is sys.argv in Python?
The sys argv list is a list that contains command line arguments in a python program. Whenever we run a python program from a command line interface, we can pass different arguments to the program. The program stores all the arguments and the file name of the python file in the sys.argv list.
The first element of the sys argv list contains the name of the python file. The second element onwards contains the command line arguments.
You can also find the total number of command line arguments to a program. For this, you can find the length of the sys.argv list using the len() function. The len() function takes the list as its input and returns the length of the sys argv list. The total number of arguments in a python program is one less than the length of the sys.argv list.
If you are going to work with command line arguments, you probably want to use sys.argv.
To learn more about sys.argv list, you can read this article on command line arguments in python.
Sys.argv Example
To use sys argv, you will first have to import the sys module. Then, you can obtain the name of the python file and the value of the command line arguments using the sys argv list.
- The sys.argv list contains the name of the python file at index 0.
- It contains the first command line argument at index 1.
- The second command line argument is present at index 2 and so on.
You can observe this in the following example.
import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)
Output:
This is the name of the script: sysargv.py
Number of arguments in: 1
The arguments are: ['sysargv.py']
If I run it again with additional arguments, I will get this output:
This is the name of the script: sysargv.py
Number of arguments in: 3
The arguments are: ['sysargv.py', 'arg1', 'arg2']
Conclusion
In this article, we have discussed the sys argv list and its use in python. To learn more about python programming, you can read this article on open file using with open in python. You might also like this article on string manipulation in Python.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.