Potentially Useful

Writing boring posts is okay

Running a Python script with Anaconda

in: Programming Data Science

I have a Python script that needs to be run from within a specific Anaconda environment (which I’ll call environment_name) for reasons that aren’t relevant here. It was tricky to get this working, so I figured it was worth a post. Here’s what made this challenging:

The solution I landed on is to replace the typical shebang line with a block of code that looks like this:

#! /bin/sh -
':' '''Describe the script here--this script just prints the Python version'
eval "$(conda shell.bash hook)"
conda activate environment_name
exec python3 -- "$0" "$@"

import sys
print("Hello from Python", sys.version)

This approach is not without weaknesses:

I’m sharing it anyway because it did solve my problem, and I hope to save somebody else the time it took me to figure this out. Or better yet, be told the “right” way to do this from a Python/Anaconda expert.

  1. The first line of most contemporary python scripts is #!/usr/bin/env python3, which tells the shell to use python to execute the rest of the script. Since Anaconda installs additional copies of Python, sometimes it’s enough to replace this with something like #!/home/username/anaconda3/envs/environment_name/bin/python3, but that didn’t work here. ↩︎