在Jupyter Notebook中通过外壳激活新的Conda env [英] Activating a new Conda env through shell from within Jupyter Notebook

查看:159
本文介绍了在Jupyter Notebook中通过外壳激活新的Conda env的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python 3编写的Jupyter Notebook工作,我想在该Notebook中运行Python 2脚本.我想知道是否有可能在Notebook中运行Shell命令,并使这些Shell命令在不同的环境下运行.

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.

例如,如果env2是运行Python 2的Conda环境,而env3运行Python 3,而我的Jupyter Notebook在env3中运行,也许我可以在Notebook中编写: !源激活env2 ! script_that_uses_python2.py 然后继续使用Notebook中的python 3代码(并使用script_that_uses_python2.py的输出).

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).

我尝试了一下,但没有成功(!conda info --envs显示env3仍在运行).关于如何更改笔记本中间的环境,然后再回到原始环境的任何建议?

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?

推荐答案

据我所知,您无法激活另一个环境并使其正常工作.您可以做的是显式运行Python,例如

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

如果我跑步

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

在我的系统上,它仅显示Python 2目录,因此它可能会找到正确的导入.但是,该脚本中的变量将在您的笔记本中不可用.您可以让Python 2文件写出一个Pickle文件,然后尝试读取它,也许...

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...

这篇关于在Jupyter Notebook中通过外壳激活新的Conda env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆