8

Should Python library modules start with #!/usr/bin/env python?

Looking at first lines of *.py in /usr/share/pyshared (where Python libs are stored in Debian) reveals that there are both files that start with the hashbang line and those that do not.

Is there a reason to include or omit this line?

3
  • BTW is there anything wrong with just #!python ? Commented Mar 20, 2012 at 8:31
  • @Kos: yes, there is: it does not work. At least not everywhere. /usr/bin/env is used solely for portability. Commented Mar 20, 2012 at 8:35
  • 1
    And also because because the location of the actual Python interpreter will change if you're using virtualenv or some of the other popular tools. Commented Mar 20, 2012 at 8:42

3 Answers 3

8

The reason why some files in /usr/share/pyshared have declared the shebang & some do not are easy to explain. Take the files uno.py and pyinotify.py. The former has no shebang and the latter has.

  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() 

You can hardcode the python binary in the shebang, but as others have mentioned, using /usr/bin/env will make it more portable.

Sign up to request clarification or add additional context in comments.

Comments

5

This line is a Shebang line. For details, please consult the wikipedia article. Basically, it specifies the interpreter with which the file can be executed if directly run from the command line.

There is no need to include this line on the top of a file unless you are planning to directly run it from the shell. Some Python modules (e.g. ftplib) have some functionality when you directly run them. These will have the #! line on top. Most don't have such functionality and therefore don't need this line.

Comments

0

if you want your script to be an executable, you have to include this line

3 Comments

This does not directly answer the question. Please improve your answer.
If I do not, is there a reason to include this line? There is nothing executable on the top level, only definitions.
-1. This answer is incorrect. This line is used to specify an interpreter and not to "make the script and executable". The latter is achieved by changing file permissions (on UNIX).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.