Python Hashbang/Shebang

Until recently, I barely knew about Hashbangs or Shebangs other than, when building a shell script, you have to put #!/bin/bash at the first line of the file.

What I wasn't aware is that you can create scripts out of many file types, because the hashbang is a declaration of which interpreter to use when running the script... which means that you can run things like Python files as scripts.

Python works as a really good cross-platform language because the os and sys libraries allow to build platform-independent code (e.g. via path.join). But there is a small catch that you need to be aware of when marking a file as a script.

In general, you should strive for always pointing to python3:

#!/usr/bin/env python3

But if you still need to use python 2 (remember it reached end of life January 2020!) you should instead use python2:

#!/usr/bin/env python2

And, if you really need compatibility with both versions of python, the only solution is to use the generic python, because you can't specify both previous ones:

#!/usr/bin/env python

But here is the trick: Depending on the operating system, and especially on the more recent versions of Ubuntu, MacOS and the like, both the installed python version and/or any downloaded one might only be installed as python3. There is no guarantee that there will exist a symlink to the generic python (and can be dangerous to manually setup one).

How to solve supporting both versions then? Well, after reading the PEP-394, they advise to only use python if you plan to run the python script inside a virtual environment (venv or virtualenv).

So there you have it, a two-step approach to support both versions at once:

a) Always run the script inside a virtualenv (easy if you use Docker nowadays)

b) Define the shebang as

#!/usr/bin/env python

Tags: Development

Python Hashbang/Shebang article, written by Kartones. Published @