Python 脚本头 [英] Python script header
问题描述
典型的标题应该是
#!/usr/bin/env python
但我发现下面在执行像 $python ./my_script.py
But I found below also works when executing the script like $python ./my_script.py
#!/usr/bin/python
#!python
这两个标题有什么区别?第二个可能是什么问题?还请讨论 python 解释器是否在 PATH 中的情况.谢谢.
What's difference between these 2 headers? What could be the problem for 2nd one? Please also discussing the case for python interpreter is in PATH or not. Thanks.
推荐答案
首先,任何时候你使用解释器显式运行脚本,如
First, any time you run a script using the interpreter explicitly, as in
$ python ./my_script.py
$ ksh ~/bin/redouble.sh
$ lua5.1 /usr/local/bin/osbf3
#!
行总是被忽略.#!
行仅是 可执行 脚本的 Unix 特性,您可以在 execve(2)
的手册页.在那里您会发现 #!
后面的单词必须是有效可执行文件的路径名.所以
the #!
line is always ignored. The #!
line is a Unix feature of executable scripts only, and you can see it documented in full on the man page for execve(2)
. There you will find that the word following #!
must be the pathname of a valid executable. So
#!/usr/bin/env python
执行用户 $PATH
上的任何 python
.这种形式对于被移动的 Python 解释器是有弹性的,这使得它在某种程度上更具可移植性,但这也意味着用户可以通过在 $PATH
中放置一些东西来覆盖标准的 Python 解释器.根据您的目标,这种行为可能好也可能不好.
executes whatever python
is on the users $PATH
. This form is resilient to the Python interpreter being moved around, which makes it somewhat more portable, but it also means that the user can override the standard Python interpreter by putting something ahead of it in $PATH
. Depending on your goals, this behavior may or may not be OK.
接下来,
#!/usr/bin/python
处理Python解释器安装在/usr/bin
中的常见情况.如果它安装在其他地方,你就输了.但这是确保您获得所需版本的好方法,否则什么都没有(失败停止"行为),如
deals with the common case that a Python interpreter is installed in /usr/bin
. If it's installed somewhere else, you lose. But this is a good way to ensure you get exactly the version you want or else nothing at all ("fail-stop" behavior), as in
#!/usr/bin/python2.5
最后,
#!python
仅当脚本运行时当前目录中存在 python
可执行文件时才有效.不推荐.
works only if there is a python
executable in the current directory when the script is run. Not recommended.
这篇关于Python 脚本头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!