You can easily pass command line arguments to Python scripts. In this tutorial, we will help you read command line arguments in Python scripts.
Below is a sample Python script that reads command line arguments and prints details. Create a sample script (such as linuxmi.py) and copy the following content.
#!/usr/bin/python
import sys
# Print the total number of parameters
print ('Total number of parameters:', format(len(sys.argv)))
#Print all parameters
print ('Parameter list:', str(sys.argv))
#Print parameters one by one
print ('First parameter:', str(sys.argv[0]))
print ('Second parameter:', str(sys.argv[1]))
print ('Third parameter:', str(sys.argv[2]))
print ('The fourth parameter:', str(sys.argv[3]))
Then execute the above script using command line arguments.
[linuxmi@linux:~/www.linuxmi.com]$ python3 linuxmi.py first 2 third 4.5
You will see the following results. The first parameter is always the script itself.
Total number of parameters: 5
Parameter list: ['linuxmi.py', 'first', '2', 'third', '4.5']
First parameter: linuxmi.py
Second parameter: first
Third parameter: 2
The fourth parameter: third
OK, that's it.