Python shebang line

Python shebang line

本问题已经有最佳答案,请猛点这里访问。

我见过一些人在env之后用空格来写他们的shebang行。如。

1
#!/usr/bin/env python

这是打字吗?

我从来没有用过空间。我用

1
#!/usr/bin/env/python

有人能解释一下吗?


不使用空间不是一个打字错误,但会导致在不同的计算机上执行同一个文件时出现可移植性问题。shebang行(#!/usr....的目的是指示在执行文件中的代码时要使用什么解释器。根据维基百科:

The form of a shebang interpreter directive is as follows:

#!interpreter [optional-arg]

in which interpreter is an absolute path to an executable program. The optional argument is a string representing a single argument.

您提供的示例#!/usr/bin/env python实际上向shell表明,在执行文件时要使用的解释器是用户路径中存在的第一个Python解释器。shebang行是这样写的,以确保可移植性:

Shebangs must specify absolute paths (or paths relative to current working directory) to system executables; this can cause problems on systems that have a non-standard file system layout. Even when systems have fairly standard paths, it is quite possible for variants of the same operating system to have different locations for the desired interpreter. Python, for example, might be in /usr/bin/python, /usr/local/bin/python, or even something like /home/username/bin/python if installed by an ordinary user.

Because of this it is sometimes required to edit the shebang line after copying a script from one computer to another because the path that was coded into the script may not apply on a new machine, depending on the consistency in past convention of placement of the interpreter. For this reason and because POSIX does not standardize path names, POSIX does not standardize the feature.

Often, the program /usr/bin/env can be used to circumvent this limitation by introducing a level of indirection. #! is followed by /usr/bin/env, followed by the desired command without full path, as in this example:

#!/usr/bin/env sh


不,这不是打字错误!您所使用的程序不适用于所有操作系统,例如,在我的Ubuntu Linux实现中,"env"是/usr/bin中的程序,而不是目录,所以!/usr/bin/env/python不起作用。