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

后端 未结 4 1714
悲哀的现实
悲哀的现实 2020-12-30 04:35

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
         


        
4条回答
  •  北海茫月
    2020-12-30 05:32

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

提交回复
热议问题