如何在使用不同内核的笔记本上运行Jupyter笔记本?

5

我想在一个Python的notebook中运行一个Jupyter的notebook(R)。使用以下命令:

%run "DESeq2 Analysis.ipynb"

调用Notebook并运行时出现了Python错误。被调用的Notebook(DESeq2 Analysis.ipynb)应该使用R内核运行。当我单独运行DESeq2 Analysis.ipynb时,它可以在R内核下正常运行。看起来发生的情况是使用Python 3内核运行的调用Notebook正在调用DESeq2 Analysis.ipynb,并尝试使用Python 3内核而不是R内核运行代码。
是否有一种方法可以在使用%run命令时指定内核?

这个答案指出了通过 nbconvert 实现这一点的方法:https://dev59.com/hqbja4cB1Zd3GeqPfmfH#47053020 - Jacques Gaudin
1个回答

1

来自@Louise Davies的答案,针对Jupyter是否可以在Python笔记本中运行一个独立的R笔记本?

I don't think you can use the %run magic command that way as it executes the file in the current kernel.

Nbconvert has an execution API that allows you to execute notebooks. So you could create a shell script that executes all your notebooks like so:

#!/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

Since your notebooks require no shared state this should be fine. Alternatively, if you really wanna do it in a notebook, you use the execute Python API to call nbconvert from your notebook.

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)

Note that this is pretty much just the example copied from the nbconvert execute API docs: link


在“预处理”步骤中,执行的笔记本是否可以访问调用笔记本中定义的当前全局变量? - PlasmaBinturong

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接