... 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脚本中以指示:
python
可执行文件,则有必要如果您手动编写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中使用
python
、python2
还是python3
,请参见PEP 394 - The "python" Command on Unix-Like Systems:任何脚本中的shebang行决定了脚本是否能够像独立的可执行文件一样执行,而无需在终端中预先键入
python
,也无需在文件管理器中双击它(如果配置正确)。这是不必要的,但通常放在那里,所以当有人看到文件在编辑器中打开,他们立即知道他们在看什么。但是,您使用的shebang行是很重要的。正确的Python 3脚本的用法是:
默认为3.latest版本。对于Python 2.7.latest,使用
python2
代替python3
。不应使用以下(除非您正在编写与Python 2.x和3.x兼容的代码):
在PEP 394中给出这些建议的原因是
python
可以引用不同系统上的python2
或python3
。它目前在大多数发行版上都是指python2
,但在某些时候可能会发生变化。另外,不要使用:
--"#!/usr/bin/env python" vs "#!/usr/local/bin/python"
相关问题 更多 >
编程相关推荐