I am reading "Learn Python the Hard Way" and was confused by the "script" part of the second line.
from sys import argv
script, filename = argv
From what I understand, the second line says: script
and filename
comprise argv
.
I tried running my code without the "script" part and it worked just fine. I'm not sure what the purpose of it is.
Generally, the first argument to a command-line executable is the script name, and the rest are the expected arguments.
Here, argv
is a list that is expected to contain two values: the script name and an argument. Using Python's unpacking notation, you can write
script = argv[0]
filename = argv[1]
as
script, filename = argv
while also throwing errors if there are an unexpected number of arguments (like one or three). This can be a good idea, depending on one's code, because it also ensures that there are no unexpected arguments.
However, the following code will not result in filename
actually containing the filename:
filename = argv
This is because filename
is now the argument list. To illustrate:
script, filename = argv
print("Script:", script) # Prints script name
print("Filename:", filename) # Prints the first argument
filename = argv
print("Filname:", filename) # Prints something like ["my-script.py", "my-file.txt"]