[译]Why do people write #!/usr/bin/env python on the first line of a Python script?

时间:2022-09-14 05:40:23

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible. In Unix, an executable file that's meant to be interpreted can indicate what interpreter to use by having a #! at the start of the first line, followed by the interpreter (and any flags it may need). If you're talking about other platforms, of course, this rule does not apply (but that "shebang line" does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).

如果你的电脑安装了多个版本的Python,/usr/bin/env将会确保解释器第一个是你环境的$PATH,替代的方法使用像#!/usr/bin/python硬编码的方式也可以,只是不太灵活。

在Unix系统中,在第一行用#!后面跟随解释器符号,来表明一个可是文件简要被什么解释器解释执行。

如果你的话说的是其他平台的话,当然这些规则并不适用,(但是"shebang行"并没有坏处,而且如果你将此脚本拷贝到类Unix的系统(Linux,Mac等)时会非常有帮助。)