我应该放#!(shebang)在Python脚本中,应该采用什么形式?

2024-04-20 12:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该把shebang放在我的Python脚本中吗?以什么形式?

#!/usr/bin/env python 

或者

#!/usr/local/bin/python

这些是同样便携的吗?哪种形式最常用?

注意:项目使用shebang。另一方面,Django项目没有


Tags: 项目djangoenv脚本binusrlocal形式
3条回答

这真的只是口味的问题。添加shebang意味着人们可以根据需要直接调用脚本(假设它被标记为可执行的);省略它只意味着必须手动调用python

运行程序的最终结果不会受到任何影响;这只是手段的选择。

Should I put the shebang in my Python scripts?

将shebang放入Python脚本中以指示:

  • 此模块可以作为脚本运行
  • 它是只能在python2、python3上运行,还是与python2/3兼容
  • 在POSIX上,如果希望直接运行脚本而不显式调用python可执行文件,则有必要

Are these equally portable? Which form is used most?

如果您手动编写shebang,请始终使用#!/usr/bin/env python,除非您有特定的理由不使用它。即使在Windows(Python启动程序)上也可以理解此表单。

注意:安装的脚本应该使用特定的python可执行文件,例如/usr/bin/python/home/me/.virtualenvs/project/bin/python。如果你在shell中激活了一个virtualenv,那么如果某个工具坏了,那就很糟糕了。幸运的是,在大多数情况下,setuptools或您的发行包工具会自动创建正确的shebang(在Windows上,setuptools可以自动生成包装器.exe脚本)。

换句话说,如果脚本在源代码签出中,那么您可能会看到#!/usr/bin/env python。如果安装了shebang,则它是指向特定python可执行文件(如#!/usr/local/bin/python)的路径(注意:不应手动编写后一类的路径)。

要选择在shebang中使用pythonpython2还是python3,请参见PEP 394 - The "python" Command on Unix-Like Systems

  • ... python should be used in the shebang line only for scripts that are source compatible with both Python 2 and 3.

  • in preparation for an eventual change in the default version of Python, Python 2 only scripts should either be updated to be source compatible with Python 3 or else to use python2 in the shebang line.

任何脚本中的shebang行决定了脚本是否能够像独立的可执行文件一样执行,而无需在终端中预先键入python,也无需在文件管理器中双击它(如果配置正确)。这是不必要的,但通常放在那里,所以当有人看到文件在编辑器中打开,他们立即知道他们在看什么。但是,您使用的shebang行是很重要的。

正确的Python 3脚本的用法是:

#!/usr/bin/env python3

默认为3.latest版本。对于Python 2.7.latest,使用python2代替python3

不应使用以下(除非您正在编写与Python 2.x和3.x兼容的代码):

#!/usr/bin/env python

PEP 394中给出这些建议的原因是python可以引用不同系统上的python2python3。它目前在大多数发行版上都是指python2,但在某些时候可能会发生变化。

另外,不要使用:

#!/usr/local/bin/python

"python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail."

--"#!/usr/bin/env python" vs "#!/usr/local/bin/python"

相关问题 更多 >