Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put #! (shebang) in Python scripts, and what form should it take?

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.

like image 301
treecoder Avatar asked Aug 02 '11 06:08

treecoder


2 Answers

It's really just a matter of taste. Adding the shebang means people can invoke the script directly if they want (assuming it's marked as executable); omitting it just means python has to be invoked manually.

The end result of running the program isn't affected either way; it's just options of the means.

like image 29
Amber Avatar answered Oct 13 '22 23:10

Amber


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.

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"

like image 152
GlassGhost Avatar answered Oct 14 '22 00:10

GlassGhost