• Uncategorized

About python : How-do-I-activate-a-conda-environment-on-linux-through-a-python-script

Question Detail

I need to make the statement: “conda activate [environment name]” work inside of a python script. As far as I can tell, it seems conda activate [env name] only works when writing directly to the terminal on Linux. I’ve tried os.system("conda activate [env name]") and even subprocess.run("conda activate [env name]"), but I always get this error after running the python script:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'. To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

I’ve also tried activating my conda environment beforehand, then running a python script that has “conda deactivate” and that does not work either. Anyone know a solution to this? Is it only possible to have the environment activated only for the duration of the script, and not have it turn on the environment in the terminal after it is ran?

For reference I have conda 4.11.0 and python 3.8.12.

Question Answer

You can circumvent this by creating a bash file with the following commands:

#!/bin/bash  
echo "Activating environment"
conda init <SHELL_NAME>
echo "Environment Activated"
echo "Starting Python script"
python3 /path/to/script.py
echo "I'm done!"

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.