Taylor's Blog

Atypical ramblings

#! #! Oh! Oh! Oh! She Moves! She Moves!

In my last post, I mentioned how I was unfamiliar with the #! line found at the beginning of Miguel Grinberg’s run.py script. Here’s what I have learned:

First, it’s called a “shebang” or “hash-bang.” I couldn’t find it on google because google omits special characters. However, I did learn about this awesome search engine that allows them: http://symbolhound.com/

Shebangs are mainly used on POSIX systems (Linux, Unix, etc.) and don’t really mean anything on Windows. However, Python 3.3 and later actually come included with Python Launcher for Windows which recognizes the following shebangs (which all do the same thing):

#! /usr/bin/env python
#! /usr/bin/python 
#! /usr/local/bin/python 
#! python

So what do these shebangs actually do?

Well, according to this thread, they tell the OS to search your $PATH for an interpreter called python, and to run the script using it.

The reason shebangs looks so weird is because they are designed for POSIX systems which have a different directory structure. The #! /usr/bin/env python shebang tells your OS to use the interpreter created in your virtual environment. When you activate an environment:

. . . the environment adds the location of its bin folder to the system path, so that, for example, when you type python you get the environment’s version and not the system’s one.

However, according to this StackOverflow thread:

A bin directory is created on POSIX systems only . . . Some paths within the virtualenv are slightly different on Windows: scripts and executables on Windows go in env\Scripts\instead of env/bin/ and libraries go in env\Lib\ rather than env/lib/.

And finally:

In Unix, an executable file that’s meant to be interpreted can indicate what interpreter to use by having a #! at the start of the first line, followed by the interpreter (and any flags it may need).

If you’re talking about other platforms, of course, this rule does not apply (but that “shebang line” does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).

. . .

Using env gives maximum flexibility in that the user can select the interpreter to use by changing the PATH.

Updated: August 19, 2015 — 6:02 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

Taylor's Blog © 2015