我应该把#!(shebang) 在 Python 脚本中,它应该采用什么形式? [英] Should I put #! (shebang) in Python scripts, and what form should it take?

查看:119
本文介绍了我应该把#!(shebang) 在 Python 脚本中,它应该采用什么形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#!/usr/bin/env python

#!/usr/local/bin/python

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

注意:tornado 项目使用舍邦.另一方面,Django 项目没有.

解决方案

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

正确(默认为版本 3.latest)Python 3 脚本的正确用法是:

#!/usr/bin/env python3

正确用于(默认为版本 2.latest)Python 2 脚本的用法是:

#!/usr/bin/env python2

以下不应使用(除非您编写的代码与 Python 2.x 和 3.x 兼容的极少数情况除外):

#!/usr/bin/env python

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

另外,请勿使用:

#!/usr/local/bin/python

<块引用>

"python 可以安装在/usr/bin/python 或/bin/python 中情况下,上面的#!会失败."

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

Should I put the shebang in my Python scripts? In what form?

#!/usr/bin/env python 

or

#!/usr/local/bin/python

Are these equally portable? Which form is used most?

Note: the tornado project uses the shebang. On the other hand the Django project doesn't.

解决方案

The shebang line in any script determines the script's ability to be executed like a standalone executable without typing python beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use IS important.

Correct usage for (defaults to version 3.latest)Python 3 scripts is:

#!/usr/bin/env python3

Correct usage for (defaults to version 2.latest)Python 2 scripts is:

#!/usr/bin/env python2

The following should NOT be used (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):

#!/usr/bin/env python

The reason for these recommendations, given in PEP 394, is that python can refer either to python2 or python3 on different systems. It currently refers to python2 on most distributions, but that is likely to change at some point.

Also, DO NOT Use:

#!/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"

这篇关于我应该把#!(shebang) 在 Python 脚本中,它应该采用什么形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆