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

问题描述 投票:3回答:1

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

%run "DESeq2 Analysis.ipynb"

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

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

python r jupyter-notebook
1个回答
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复制的示例

© www.soinside.com 2019 - 2024. All rights reserved.