Activate the conda environment in Python
Does conda provide a way to activate the environment from a running Python program?
For example, each virtual environment (venv) created with virtualenv has a script venv
/bin/activate_ this.py
(assuming you are on Linux) that can be used to activate venv
in a running Python program as follows:
activate_this = '/full/path/to/venv/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))
I’m just wondering if I need to tune the activate_this.py
of virtualenv for this work (virtualenv and conda environments are slightly different in structure, so they don’t work as-is) or if there is an existing method.
Solution
I don’t think it’s possible. I’m not an expert on this, but the python interpreter for virtual environments is different. You can also see that the file will only change your system path, so the Python interpreter to use will point to the opening of the virtual environment. So I think you actually have to use the python interpreter of the virtual environment to generate a new python process in your script. Like this:
import subprocess
subprocess.run(['/full/path/to/venv/bin/python', 'path/to/script.py'])