from sys import argv – what is the function of “script”

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"]

Leave a Comment