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.
Table of Contents
Use of sys.argv
In python, 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.
1 2 |
import sys print(sys.argv) |
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 arg1
, arg2
and arg3
to the script and you can observe in the output screenshot that the list contains these added arguments.
1 |
main.py arg1 arg2 arg3 |
Note. Command Line arguments are separated with space.
As 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.argv
arguments into a string: Convert a List To String in Python - To arrange the
sys.argv
arguments 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
Examples
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[0]
will always give you the name of script that is currently being executed. Likewise sys.argv[1]
, sys.argv[2]
, sys.argv[3]
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.
1 2 3 4 5 6 |
import sys print("The name of currently executing file is: " + sys.argv[0]) print("The first user-defined argument: " + sys.argv[1]) print("The second user-defined argument: " + sys.argv[2]) print("The third user-defined argument: " + sys.argv[3]) 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
.
1 |
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!