Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the conda environment to use inside a python script

Tags:

python

conda

I need to run in the same environment a script workflow.py that use python 2.7 and another script stepA.py that use python 3.7.

Let suppose that stepA.py is called from workflow.py, one possibility is to setup two conda env, one with python2.7 and another with python3.7, run workflow.py in the py2env and write something like

subprocess.run('bash -c "source activate py3env; stepA.py"', shell=True)

in workflow.py to launch stepA.py.

I do not like this solution, instead I would like to modify the first row workflow.py and stepA.py by indicating the python version to be used, e.g.

#!/usr/bin/env python2.7

instead of simply

#!/usr/bin/env python

this second solution seems to me more atomic and dry.

I tried something like

$ conda --version
conda 4.7.12
$ conda create -n py3env python=3.8
[...]
$ conda env list
# conda environments:
base                  *  /sto1/ref/miniconda2
py3env                   /sto1/ref/miniconda2/envs/py3env
$ cat ./test.py
#!/usr/bin/env conda run -n py3env python
import os,sys
print sys.executable
print os.__file__
$ ./test.py
/usr/bin/env: conda run -n pheatmap_1 python: No such file or directory

So the conda run solution seem not working.

What is the proper way to set the environment for inside the script (in the #! row or with other strategies)?

like image 633
mox Avatar asked Dec 06 '19 12:12

mox


People also ask

How does conda change environment or code?

To do so, open the Command Palette (Ctrl+Shift+P) and enter Preferences: Open User Settings. Then set python.condaPath , which is in the Python extension section of User Settings, with the appropriate path.


1 Answers

You should be giving the full path to your python which should be given as executable

for eg:

#!/usr/bin/env /user/intelpython/latest/envs/py3env/bin/python
code

In this /user/intelpython/latest/envs/py3env/bin/python(My full path to a particular python) can be either python3 or 2 To get the absoulte path activate an environment and use which python command

like image 60
ArunJose Avatar answered Sep 21 '22 00:09

ArunJose