I\'m currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1]
represents. Is it simpl
sys.argv
is a attribute of the sys
module. It says the arguments passed into the file in the command line. sys.argv[0]
catches the directory where the file is located. sys.argv[1]
returns the first argument passed in the command line. Think like we have a example.py file.
import sys # Importing the main sys module to catch the arguments
print(sys.argv[1]) # Printing the first argument
Now here in the command prompt when we do this:
python example.py
It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code
.
If we run the example.py with passing a argument
python example.py args
It prints:
args
Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:
example argumentpassed
It prints:
argumentpassed
It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.
To pass arguments to your python script while running a script via command line
python create_thumbnail.py test1.jpg test2.jpg
here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg
With in the create_thumbnail.py script i use
sys.argv[1:]
which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']
sys .argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal.
Just try this:
import sys
print sys.argv
argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.
Now try this running your filename.py like this:
python filename.py example example1
this will print 3 arguments in a list.
sys.argv[0] #is the first argument passed, which is basically the filename.
Similarly, argv1 is the first argument passed, in this case 'example'
A similar question has been asked already here btw. Hope this helps!