6

I am using a python program that uses some modules installed by conda in a separate variable. So before running the script I call from unix shell the following command to source the environment:

conda activate my-rdkit-env

is it possible to call it rather inside my python script? I've tried to do it in the following manner but it did not work

import subprocess
subprocess.run('conda init bash', shell=True)
#subprocess.run('conda activate my-rdkit-env', shell=True)
1
  • did you ever end up figuring this out? if so, would love to hear the solution! thanks ~~
    – lefft
    Commented Apr 27, 2021 at 17:45

2 Answers 2

4

From this answer you should be able to execute an script directly from the environment which would relieve you from activating and deactivating environment while executing other code in the environment you are working.

process = subprocess.Popen(
    "conda run -n ${CONDA_ENV_NAME} python script.py".split(), , stdout=subprocess.PIPE
)
output, error = process.communicate()
1

From https://github.com/conda/conda/issues/9296

Conda init registers conda as a shell function, you need to have that bit initialize your shell in order to do activation. You could do something like

. $CONDA_PREFIX/etc/profile.d/conda.sh && conda activate test4 && conda env list

So for example:

import subprocess
cmd = '. $CONDA_PREFIX/etc/profile.d/conda.sh && conda activate my-rdkit-env' 
subprocess.call(cmd, shell=True, executable='/bin/bash')

Note:

If you are already in a different conda environment when running this code, $CONDA_PREFIX will give you the prefix from that enviroment. To get the base one, just open a terminal and type $CONDA_PREFIX. Then replace $CONDA_PREFIX with what the prompt gives you (it's usually something like /home/user/anaconda3).

1
  • 1
    It doesn't work! The Python code that follows "subprocess.call(cmd, shell=True, executable='/bin/bash')" line continues to run on the initial conda environment.
    – tevang
    Commented Mar 11, 2022 at 22:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .