Ubuntu – How to make python shebang use python3

bashbashrcpython3shebang

I have a third party script that uses the shebang #!/usr/bin/env python.

According to the python documentation, this is the correct form for scripts that are suitable for both Python v2 and Python v3 (https://docs.python.org/3/using/windows.html#shebang-lines).

My Ubuntu (WSL) has only Python 3 installed:

~❯ which python
~❯ which python3
/usr/bin/python3

I have added this to the path, by adding the following in my ~/.bashrc and sourcing it

export PATH=/usr/bin/python3:${PATH}
export PY_PYTHON=3  # also added this for good measure, but no joy
~❯ . ~/.bashrc
~❯ env | grep PATH
PATH=/home/me/.local/bin:/home/me/bin:/usr/bin/python3:/opt/gradle/gradle-5.3.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

Yet when I run this script it complains that it cannot find Python. I have created a short test file foo that contains the same shebang and a print("Hello"):

~❯ ./foo
/usr/bin/env: ‘python’: No such file or directory

What else can I do to make env use python3?

PS: I do not have python 2, nor do I wish to install it. The third party script's README specifically mentions supporting both Python v2 and v3, and the shebang indicates this, as mentioned, according to the Python docs themselves.

PPS: Adding aliases does not resolve this as they are only effective when the user is calling python at the prompt, not when the bash itself is running a script. This answer to a similar question explicitly cites this behaviour: https://askubuntu.com/a/351380/333103

PPPS: The received wisdom from other questions is that symlinking is not the correct solution to env issues (don't have link to hand just ATM)

Best Answer

Since OP does not install python2 and doesn't need /usr/bin/python as python2, I'm suprised that no one mentioned the most simple solution.

You just symbolic link python to python3 with sudo ln -s python3 /usr/bin/python, and it will work.

Or, config the alternatives as mentioned in the comment(3.6 if you're using Ubuntu 18.04 on WSL):

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 100