I installed python2.7 and pyhton3.5 with apt-get.
In my .bashrc I have alias python=python3 to make python3 the default. This works if I just run python directly, but it doesn't seem to work with /usr/bin/env.

How can I force python3 in this case?

$ python --version
Python 3.5.2
$ /usr/bin/env python --version
Python 2.7.12
  • You can type python3 instead python, so in script you can type: #!/usr/bin/env python3 – Benny Aug 26 '16 at 20:00
  • 1
    yes, but I'm using scripts not made by me. I prefer not to change them. – r03 Aug 26 '16 at 20:01
  • 3
    Python2 and python3 are not compatible. Those scripts probably expect python 2 – Hack Saw Aug 26 '16 at 20:04

That's because env is searching python in your PATH, not on any shell builtin, or alias or function. As you have defined python as python3 as an alias, env won't find it, it will search through PATH and will resolve python to /usr/bin/python (which is python2).

You can check all the available locations of executable python, in bash, do:

type -a python

You are out of luck if you want to use an alias in shebang as by definition, shebang needs to be an full path to the interpreter executable, which the env should resolve python to when you use /usr/bin/env python. To interpret the script using python3 use the shebang:

#!/usr/bin/env python3
  • Thanks. I made it work like this for now: 'ln -s /usr/bin/python3 ~/bin/python'. ~/bin is first in the PATH. – r03 Aug 26 '16 at 20:21
  • 2
    @r03 Don't do that, look at virtualenv instead. – heemayl Aug 26 '16 at 20:29
  • ok, that may be the best solution. Thanks – r03 Aug 26 '16 at 20:35

Given the number of script which call /usr/bin/env python expecting python 2, it's probably a bad idea to have python actually be python 3.

As Benny said in a comment, /usr/bin/env python3 is the right solution.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.