Python库模块是否应该以 #!/usr/bin/env python 开头?

8

Python库模块是否应该以#!/usr/bin/env python开头?

查看Debian中存储Python库的/usr/share/pyshared*.py文件的第一行,发现有些文件以hashbang行开头,而有些则没有。

包含或省略此行的原因是什么?


顺便问一下,只用 #!python 有什么问题吗? - Kos
@Kos:是的,有一个问题:它不起作用。至少不是在所有地方。/usr/bin/env 仅用于可移植性。 - Mischa Arefiev
1
而且,由于如果您使用virtualenv或其他一些流行的工具,实际Python解释器的位置会发生变化。 - Noufal Ibrahim
3个回答

7

为什么在/usr/share/pyshared文件夹中有些文件声明了shebang,而有些则没有?这很容易解释。以uno.pypyinotify.py这两个文件为例,前者没有shebang,后者有。

  1. uno.py is a python module which will be imported and used in other programs/scripts. Thus it will never be executed directly from the command line.
  2. On the other hand pyinotify.py contains the shebang and you can see that it contains the following line at the bottom (it can made into an executable if you run a chmod u+x on it):

    if __name__ == '__main__':
        command_line()
    

您可以在shebang中硬编码Python二进制文件,但正如其他人所提到的那样,使用/usr/bin/env将使其更具可移植性。


5
这行代码是Shebang行。具体细节请参考维基百科文章。基本上,它指定了解释器,使得文件可以在命令行直接运行。
除非您计划从shell直接运行文件,否则不需要在文件顶部包含此行。一些Python模块(例如ftplib)在直接运行时具有某些功能。这些将在顶部有#!行。大多数模块没有这样的功能,因此不需要这行代码。

0
如果你想让你的脚本变成可执行文件,你必须包含这一行。

1
这并没有直接回答问题。请改进你的回答。 - Tadeck
如果我不这样做,是否有包含这行代码的理由?在顶层没有可执行的内容,只有定义。 - Mischa Arefiev
6
这个答案是不正确的。这行代码用于指定解释器,而不是“使脚本可执行”。后者可以通过更改文件权限(在UNIX系统上)来实现。 - Noufal Ibrahim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接