来自sys import argv-“脚本"的功能是什么? [英] from sys import argv - what is the function of "script"
问题描述
我正在阅读艰难地学习Python",但对第二行的脚本"部分感到困惑.
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
据我了解,第二行说: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.
在这里,argv
是一个预期包含两个值的列表:脚本名称和参数.使用Python的拆包符号,您可以编写
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]
为
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.
但是,以下代码不会导致filename
实际上包含文件名:
However, the following code will not result in filename
actually containing the filename:
filename = argv
这是因为filename
现在是参数列表.为了说明:
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"]
这篇关于来自sys import argv-“脚本"的功能是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!