This is a detailed tutorial on Python sys.argv. Learn to parse and read the command line arguments in your python program using the sys.argv list.
Use of sys.argv
sys.argv is basically a Python List that contains command-line arguments passed to the script that is being currently executed. Command-line arguments are often helpful to take inputs from the user to the python program.
To make use of
sys.argv, you first have to import the sys module into your python program. You need not explicitly install the sys module as it comes pre-installed with python. The following lines of code show that
sys.argv contains a list of command-line arguments.
Observe the following code and the output screenshot. You can clearly see it contains a list and the list currently contains only one element and that is main.py which is the name of the file which is currently being executed. So, the first argument of the list
sys.argv is always the name of the file that is being executed.
Now, for the demonstration, I’ve provided three more command-line argument
arg3 to the script and you can observe in the output screenshot that the list contains these added arguments.
main.py arg1 arg2 arg3
Note. Command Line arguments are separated with space.
sys.argv is a list, you can perform all of the operations that can be performed on any of the other python lists. I’ve listed below some of our python list tutorials.
- To convert the
sys.argvarguments into a string: Convert a List To String in Python
- To arrange the
sys.argvarguments in ascending or descending order: Python Sort List using sort() Method
- To find the number of command-line arguments in
sys.argv:Find Size of a List In Python
The examples of each of these are given below.
You can traverse any particular command-line argument using indexes on the sys.argv list. Remember that
sys.argv will always give you the name of script that is currently being executed. Likewise
sys.argv and so on will give you the command line arguments according to the specified indexes.
You can simply apply the
len() function on the
sys.argv list to find the number of command-line arguments.
print("The name of currently executing file is: " + sys.argv)
print("The first user-defined argument: " + sys.argv)
print("The second user-defined argument: " + sys.argv)
print("The third user-defined argument: " + sys.argv)
print("Total Number of Command-Line Arguments: " + str(len(sys.argv)))
We’ve typed the following command in the console to run the above code saved in a file named
main.py arg1 arg2 arg3
I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!