如何从具有不同内核的笔记本运行Jupyter笔记本?

时间:2017-12-18 19:26:22

标签: python r jupyter-notebook

我试图在笔记本(Python)中运行Jupyter笔记本(R)。使用命令:

--replicas n

调用Noteook并运行它,但会出现Python错误。正在调用的笔记本(DESeq2 Analysis.ipynb)应该与R内核一起运行。当我独立运行时,DESeq2 Analysis.ipynb与R内核运行良好。似乎正在发生的事情是使用Python 3内核运行的调用笔记本调用DESeq2 Analysis.ipynb并尝试使用Python 3内核而不是R内核运行代码。

使用%run命令时有没有办法指定内核?

1 个答案:

答案 0 :(得分:0)

从@Louise Davies answerCan Jupyter run a separate R notebook from within a Python notebook?

  

我不认为你可以在执行当前内核中的文件时使用%run magic命令。

     

Nbconvert有一个执行API,允许您执行笔记本。因此,您可以创建一个shell脚本来执行所有笔记本,如下所示:

#!/bin/bash
jupyter nbconvert --to notebook --execute 1_py3.ipynb
jupyter nbconvert --to notebook --execute 2_py3.ipynb
jupyter nbconvert --to notebook --execute 3_py3.ipynb
jupyter nbconvert --to notebook --execute 4_R.ipynb
     

由于您的笔记本电脑不需要共享状态,因此这应该没问题。或者,如果您真的想在笔记本中使用它,可以使用execute Python API从笔记本中调用nbconvert。

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor

with open("1_py3.ipynb") as f1, open("2_py3.ipynb") as f2, open("3_py3.ipynb") as f3, open("4_R.ipynb") as f4:
    nb1 = nbformat.read(f1, as_version=4)
    nb2 = nbformat.read(f2, as_version=4)
    nb3 = nbformat.read(f3, as_version=4)
    nb4 = nbformat.read(f4, as_version=4)

ep_python = ExecutePreprocessor(timeout=600, kernel_name='python3')
#Use jupyter kernelspec list to find out what the kernel is called on your system
ep_R = ExecutePreprocessor(timeout=600, kernel_name='ir')

# path specifies which folder to execute the notebooks in, so set it to the one that you need so your file path references are correct
ep_python.preprocess(nb1, {'metadata': {'path': 'notebooks/'}})
ep_python.preprocess(nb2, {'metadata': {'path': 'notebooks/'}})
ep_python.preprocess(nb3, {'metadata': {'path': 'notebooks/'}})
ep_R.preprocess(nb4, {'metadata': {'path': 'notebooks/'}})

with open("1_py3.ipynb", "wt") as f1, open("2_py3.ipynb", "wt") as f2, open("3_py3.ipynb", "wt") as f3, open("4_R.ipynb", "wt") as f4:
    nbformat.write(nb1, f1)
    nbformat.write(nb2, f2)
    nbformat.write(nb3, f3)
    nbformat.write(nb4, f4)
     

请注意,这只是从nbconvert执行API文档中复制的示例:link