Python shebang 行

Python shebang line

我看到有些人在 env 之后用 space 写他们的 shebang 行。 例如。

#!/usr/bin/env python

这是打字错误吗?

我从不使用 space。我用

#!/usr/bin/env/python

有人可以澄清一下吗?

不,这不是错字!您正在使用的那个不适用于所有 os。例如。在我的 Ubuntu Linux 实现中 'env' 是 /usr/bin 中的程序而不是目录,所以 #!/usr/bin/env/python 将无法工作.

不使用 space 不是拼写错误,但会导致在不同机器上执行同一文件时出现可移植性问题。 shebang 行 (#!/usr....) 的目的是指示在执行文件中的代码时要使用的解释器。根据Wikipedia:

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 行是这样写的 ensure portability:

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