from sys import argv - “脚本"的功能是什么? [英] from sys import argv - what is the function of "script"

查看:39
本文介绍了from sys import argv - “脚本"的功能是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Learn Python the Hard Way",但对第二行的脚本"部分感到困惑.

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

据我所知,第二行说:scriptfilename 组成 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"]

这篇关于from sys import argv - “脚本"的功能是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆