Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you activate an Anaconda environment within a Python Script?

Tags:

I have searched through stack overflow, but no post helped specifically with Anaconda.

I am trying to my own Command line prompt in Python. But to do that, I need to activate my Anaconda environment. I cant find anywhere on the web how to run a basic python script to be able to activate said environment. Does anyone know how to do so?

like image 924
zhilothebest Avatar asked Mar 29 '16 04:03

zhilothebest


2 Answers

The following will work in Python 3.5 using the subprocess module:

subprocess.run('source activate environment-name && "enter command here" && source deactivate', shell=True)

Replace the "enter command here" with the command you want to run. You don't need the "source deactivate" at the end of the command but it's included just to be safe.

This will temporarily activate the Anaconda environment for the duration of the subprocess call, after which the environment will revert back to your original environment. This is useful for running any commands you want in a temporary environment.

like image 163
brianbhsu Avatar answered Oct 28 '22 14:10

brianbhsu


I need the same thing. But we CANNOT use source in subprocess in Linux. Here is my solution.

For a subprocess, I append the PYTHON script after a shell, in which the conda environment is setted.

# This is a Python code
script = 'python test.py'
cmd_dict = {
¦   ¦   'activate_env': 'activate_env_%s.sh' % (random.randint(1000,9999)),
¦   ¦   'script': script,
¦   ¦   'conda_name': conda_name,
¦   ¦   }
cmd = 'cp activate.sh {activate_env} && echo "{script}" >> {activate_env} && sh {activate_env} {conda_name}'.format(**cmd_dict)
env = {}
env.update(os.environ)
result = subprocess.run(cmd, shell=True, env=env)

Here is my activate.sh,

#!/bin/sh
_CONDA_ROOT="/home/***/miniconda3"
. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
_conda_activate "$@"
like image 26
Oswin Avatar answered Oct 28 '22 15:10

Oswin