Python shebang line [duplicate]

不羁的心 提交于 2019-12-13 14:18:20

问题


i've seen some people write their shebang line with a space after env. Eg.

#!/usr/bin/env python

Is this a typo?

I don't ever use a space. I use

#!/usr/bin/env/python

Can someone please clarify this?


回答1:


No it isn't a typo! The one you are using will not work on all os's. E.G. in my Ubuntu Linux implementation 'env' is a program in /usr/bin not a directory so #!/usr/bin/env/python won't work.




回答2:


Not using a space isn't a typo, but leads to portability issues when executing the same file on different machines. The purpose of the shebang line (#!/usr....) is to indicate what interpreter is to be used when executing the code in the file. According to 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.

The example you provided, #!/usr/bin/env python, actually indicates to the shell that the interpreter to be used when executing the file is the first python interpreter that exists in the user's path. The shebang line is written this way to 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



来源:https://stackoverflow.com/questions/50546892/python-shebang-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!