Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I activate a conda env in a subshell?

I've written a python program. And if I have a shebang like this one:

#!/usr/bin/python

and I make the file executable with:

$ chmod 755 program.py

I can run the program like so:

$ ./program.py

Here is the issue. I use the conda virtual environments. When I run the program like above, the system creates a subshell that does not recognize the active environment:

(my_env) $ ./program.py
ImportError: No module named pymongo

If I do it this way, however...

(my_env) $ python program.py
# blah blah... runs great

How do I specify the right environment for use in the subshell? Is it possible? I'd like to save my fingers the effort of typing the six character string that is python.

Another post, Shebangs in conda managed environments, briefly touches on this but does not provide the right answer. Instead of activating the environment in the subshell, it just says, go ahead and ignore the shebang... just use the $ python program.py syntax.

like image 775
meh Avatar asked Jan 28 '17 20:01

meh


People also ask

How do I enable conda in shell?

To initialize your shell, run $ conda init <SHELL_NAME> Currently supported shells are: - bash - fish - tcsh - xonsh - zsh - powershell See 'conda init --help' for more information and options. IMPORTANT: You may need to close and restart your shell after running 'conda init'.

How do I activate an existing conda environment?

You activate (deactivate) an environment using the conda activate ( conda deactivate ) commands. You install packages into environments using conda install ; you install packages into an active environment using pip install . Use the conda env list command to list existing environments and their respective locations.

Can I choose where my conda environment is stored?

You may change the default location by using the following command but it is not encouraged. Conda can no longer find your environment by your environment name, you will have to specify the environment's full path to activate it every time.


1 Answers

In your script, change...

#!/usr/bin/python

...to:

#!/usr/bin/env python

The python used by an activated conda environment is ${CONDA_PREFIX}/bin/python and not /usr/bin/python

Notice the difference?

(root) ~/condaexpts$ which python
/home/ubuntu/condaexpts/m3/bin/python

(root) ~/condaexpts$ /usr/bin/env python
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

(root) ~/condaexpts$ source deactivate

~/condaexpts$ which python
/usr/bin/python

~/condaexpts$ /usr/bin/env python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
like image 111
Nehal J Wani Avatar answered Oct 07 '22 15:10

Nehal J Wani