Scripting Hashbang: How to get the python 2 interpreter? Scripting Hashbang: How to get the python 2 interpreter? unix unix

Scripting Hashbang: How to get the python 2 interpreter?


Getting inspiration from a famous perl hashbang trick, I came up with this:

#!/bin/sh"""":python2 -c "" 2>/dev/null && exec python2 $0 ${1+"$@"}python  -c "" 2>/dev/null && exec python  $0 ${1+"$@"}echo "Could not find a python interpreter."exit 1"""print "hello python"


The unix way is to specify python2 - most good distros will now install 2.x as python2 and 3.x as python3, linking whichever is the main one to python (in most distros, 2.x). It is therefore best to specify the one you want explicitly.

This is all defined in PEP 394 which states:

This PEP provides a convention to ensure that Python scripts can continue to be portable across *nix systems, regardless of the default version of the Python interpreter (i.e. the version invoked by the python command).

  • python2 will refer to some version of Python 2.x
  • python3 will refer to some version of Python 3.x
  • python should refer to the same target as python2 but may refer to python3 on some bleeding edge distributions

So if a distro isn't doing this, it is essentially a bug on their end.


If you must run on python 2, you best also call the interpreter as python2. I think most UNIX releases have symlinks from /usr/bin/python/and /usr/bin/python2 to the appropriate binary.