Search code examples
pythoncondashebang

Python shebang with conda


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?


Solution

  • 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.