Python shebang with conda

Question:

Following best practice I have started an executable Python script with a shebang specific to Python 3:

#!/usr/bin/env python3

import spotipy

# ...some fancy code

One chmod +x later, I’m executing this script as ./quick_example.py but alas the executable found (running locally on my Mac) is not the Python executable in my active Conda environment, as running which python3 in my Bash shell throws up /usr/bin/python3 instead of the desired /Users/anilkeshwani/opt/miniconda3/envs/spot/bin/python given by which python.

Apparently using #!/usr/bin/env python is bad practice in general, so my question is: can I keep the Python 3-specific shebang and somehow have Conda alias python3 calls when an env is active?

Asked By: Anil

||

Answers:

So, I’m not sure what you’ve read. Unfortunately, the naming convention across *nix platforms is a total mess. IMO, python should just always be Python 3, since Python 2 is passed the EOL. But this is above my pay grade. In any case, looking at PEP 394:

For scripts that are only expected to be run in an activated virtual
environment, shebang lines can be written as #!/usr/bin/env python, as
this instructs the script to respect the active virtual environment.

It gets messy for scripts not expected to be run in a virtual environment.

TL:DR

Just use #!/usr/bin/env python

Edit

Ah, looking at the answer you linked to, they were referencing and old version of PEP 394 which has been revised several times since that answer was posted. A total mess, unfortunately.

Answered By: juanpa.arrivillaga

Noting the answer by juanpa, I think your problem may be in that you haven’t activated your conda environment in the shell in which you are running ./quick_example.py.

Activating a conda environment is done by running source activate <envname>. Just creating the env isn’t enough, you have to activate it as well before it takes effect. This has to be done each time you create a new shell, although IDEs often have ways to have this be done automatically.

Answered By: Jonathan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.