Python源头注释
这一行是用来做什么的?
#!/usr/bin/env python
python 脚本的第一行中的
What is the line
#!/usr/bin/env python
in the first line of a python script used for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 UNIX 和 Linux 中,这告诉使用哪个二进制文件作为解释器(另请参阅Wiki 页面 )。
例如 shell 脚本由
/bin/sh
解释。现在使用 python 有点棘手,因为你无法假设二进制文件安装在哪里,也无法假设你想使用哪个。 这就是
/usr/bin/env
技巧。 它使用$PATH
中第一个的 python 二进制文件。 您可以检查执行which python
使用解释器行,您可以通过将脚本 chmod 为可执行文件来运行脚本。 只需运行它即可。 因此,以
这两种方法开头的脚本是等效的:
并且(假设您之前已经完成了
chmod +x script.py
)这对于创建系统范围的脚本很有用。
然后你可以从任何地方调用它
In UNIX and Linux this tells which binary to use as an interpreter (see also Wiki page).
For example shell script is interpreted by
/bin/sh
.Now with python it's a bit tricky, because you can't assume where the binary is installed, nor which you want to use. Thus the
/usr/bin/env
trick. It's use whichever python binary is first in the$PATH
. You can check that executingwhich python
With the interpreter line you can run the script by chmoding it to executable. And just running it. Thus with script beginning with
these two methods are equivalent:
and (assuming that earlier you've done
chmod +x script.py
)This is useful for creating system wide scripts.
And then you call it from anywhere just with
这称为 shebang 行:
This is called a shebang line:
在 UNIX 和类似的操作系统下,此行告诉执行文件时将使用哪个解释器。
Under UNIX and similar operating systems, this line tells which interpreter is to be used if the file is executed.
正如安德里所说。 在 Windows 中,从命令行启动时运行文件的可执行文件依赖于关联:
在 Unix 中,shell 解释器通过打开文件并查看文件中是否有指定的命令来进行推断。
As Andri said. In Windows, the executable to run a file with when launched from the command line relies on an association:
In Unix, the shell interpreter makes the inference by opening the file and seeing if there is a command named in the file.
'/usr/bin/env python' 在 $PATH 中搜索 python 并运行它。
,如果您只是尝试不指定解释器运行该文件,那么该行的作用是告诉您的计算机如何处理该文件。 debian.net/viewtopic.php?t=36789" rel="nofollow noreferrer">更多详细信息
'/usr/bin/env python' searches $PATH for python and runs it.
What that line does is tell your computer what to do with that file, if you simply try to run the file without specifying an interpreter.. more detail
请注意,这一行只不过是对 Windows 中的解释器的注释。
Just a note, this line is nothing more then a comment to the interpreter in Windows.