You can easily pass command line arguments to a Python script. In this tutorial, we will help you to read the command line arguments in a Python script.
Below is the sample Python script, which reads the command line arguments and print details. Create a sample script like script.py and copy the below content.
Advertisement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/python import sys # Print total number of arguments print ('Total number of arguments:', format(len(sys.argv))) # Print all arguments print ('Argument List:', str(sys.argv)) # Print arguments one by one print ('First argument:', str(sys.argv[0])) print ('Second argument:', str(sys.argv[1])) print ('Third argument:', str(sys.argv[2])) print ('Fourth argument:', str(sys.argv[3])) |
Then execute the above script with command line parameters.
python script.py first 2 third 4.5
You will see the results below. The first argument is always the script itself.
OutputTotal number of arguments: 5 Argument List: ['script.py', 'first', '2', 'third', '4.5'] First argument: script.py Second argument: first Third argument: 2 Fourth argument: third