Activating a new Conda env through shell from within Jupyter Notebook

浪尽此生 提交于 2021-01-29 03:17:53

问题


I'm working with a Jupyter Notebook written in Python 3, and I would like to run Python 2 scripts from within that Notebook. I was wondering if it's possible to run Shell commands from within the Notebook, and have these Shell commands running under a different environment.

For example, if env2 is a Conda environment that runs Python 2, and env3 runs Python 3, and my Jupyter Notebook runs in env3, maybe I could write within my Notebook: ! source activate env2 ! script_that_uses_python2.py and then continue with python 3 code that is in the Notebook (and uses the output of script_that_uses_python2.py).

I tried it and it didn't work (! conda info --envs showed that env3 is still running). Any advice on how to change the environment in the middle of the Notebook and then go back to the original environment?


回答1:


As far as I know, you cannot activate another environment and have it work like that. What you can do is run that Python explicitly, something like

!/path/to/anaconda/envs/python2env/bin/python script_that_uses_python2.py

If I run

!/path/to/anaconda/envs/python2env/bin/python -c "import sys; print sys.path"

on my system, it only shows Python 2 directories, so it would probably find the correct imports. However, the variables from that script won't be available in your notebook. You could have the Python 2 file write out a Pickle file and try to read that, maybe...



来源:https://stackoverflow.com/questions/39479898/activating-a-new-conda-env-through-shell-from-within-jupyter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!