Search code examples
pythoncondaanaconda3

switch conda environment from within python script


Is it possible at all to launch a Python script using conda environment ENV1 and at some point within the script to switch to environment ENV2 and the code that follows that point to be executed within ENV2 instead of ENV1? I have tried the following suggested solution but it doesn't work:

https://unix.stackexchange.com/questions/622383/subprocess-activate-conda-environment-from-python-script?newreg=191cf527472141d2a76a244969897af8

Below is an example script. Assuming that I launch the script while having ENV1 as my active environment:

import subprocess

print("Changing Conda virtual environment to 'ENV2'.")
cmd = '. $CONDA_PREFIX_1/etc/profile.d/conda.sh && conda activate ENV2 && echo $CONDA_PREFIX'
subprocess.call(cmd, shell=True, executable='/bin/bash')
print(os.environ['CONDA_PREFIX'])

The only viable solution I could think of is to save all code that occurs after "subprocess.call(cmd, shell=True, executable='/bin/bash')" into a separated script named "script_for_ENV2.py" and replace the above script with this:

import subprocess

cmd = 'conda run -n ENV2 script_for_ENV2.py'
subprocess.call(cmd, shell=True, executable='/bin/bash')

Solution

  • Is it possible at all to launch a Python script using conda environment ENV1 and at some point within the script to switch to environment ENV2 and the code that follows that point to be executed within ENV2 instead of ENV1?

    No, this isn't possible, at least not at a practical level, since launching a python script creates a process running in the underlying operating system.

    One possibility is that you can launch another python script using whatever conda environment you want. But why do you want to do this?