Python provides the sys.argv
module, in order to read the arguments, passed via the command-line interface. Generally, when a Python script is called via the command line interface some arguments, options or parameters can be passed. In this tutorial, we examine the sys.argv which is a list that contains provided parameters as items.
Print All Parameters
The sys.argv
is a list that contains all provided parameters where the first item is the name of the Python script and others are provided parameters. In the following example, we create a script named list_names.py
.
#!/bin/python3
import sys
print(str(sys.argv))
We call the list_name.py by providing some names like ismail, ahmet, ali.
$ list_names.py ismail ahmet ali
['./list_names.py', 'ismail', 'ahmet', 'ali']
Get Parameter Count
The sys.argv can store single or more parameters and there is no limit count the count of the parameters. The parameter count can be gotten by using the len()
method.
#!/bin/python3
import sys
print("Parameter count is ",len(sys.argv))
$ list_names.py ismail ahmet ali
Parameter count is 4
The script name is also provided with the sys.argv and counted as a parameter which results in the parameter count as 4.
Print First Parameter
The sys.argv is a list where multiple items are provided The script name is provided as the first item but is it not provided via the command-line interface. The script file name index number is 0 and the first parameter index number is 1.
#!/bin/python3
import sys
print("First parameter is ",sys.argv[1])
$ list_names.py ismail ahmet ali
First parameter is ismail
Read Specific Parameter
As the sys.argv is a list we can read and get specific parameters by using the index numbers. In the following example, we read the 3rd item in the list which is the 2nd parameter.
#!/bin/python3
import sys
print(sys.argv[3])
$ list_names.py ismail ahmet ali
ali