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

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

Looking at the first *.py lines in /usr/share/pyshared (where the Python libraries are stored in Debian) shows that there are both files that start with the hashbang line, and those that don't.

Is there a reason to include or omit this line?

+8
python coding-style shebang
source share
3 answers

The reason some files in /usr/share/pyshared declared shebang and some of them are not easy to explain. Take the uno.py and pyinotify.py . The former does not have shebang, but the latter does not.

  • uno.py is a python module that will be imported and used in other programs / scripts. Thus, it will never be executed directly from the command line.
  • On the other hand, pyinotify.py contains shebang, and you can see that it contains the following line below (it can be executed in an executable file if you run chmod u+x ):

     if __name__ == '__main__': command_line() 

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

+6
source share

This line is the Shebang line. See the wikipedia article for more details. Basically, it indicates the interpreter with which the file can be executed if it is executed directly from the command line.

There is no need to include this line at the top of the file unless you plan to run it directly from the shell. Some Python modules (e.g. ftplib) have some functions when you run them directly. They will have a line #! from above. Most of them do not have this functionality and therefore do not need this line.

+5
source share

if you want your script to be executable you must include this line

0
source share

All Articles