简体   繁体   中英

Activating conda environment within Python

Does conda provide for a way to activate an environment from within a running Python program?

For instance, 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 within 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 am just wondering if I need to adapt virtualenv's activate_this.py for this job (virtualenv and conda environments are structured slightly differently, so wouldn't work as is) or there's an existing way.

I think it is not possible the way you intend to. I am not an expert on this field, but the python interpreter of the virtual environment is different. You can also see that the file will only change things of you system path, so that the python interpreter to use will point to the on of the virtual environment. So I think you actually have to spawn a new python process within your script using the python interpreter of the virtual environment. Like this:

import subprocess

subprocess.run(['/full/path/to/venv/bin/python', 'path/to/script.py'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM