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?
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.
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 "$@"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With