我想将Python脚本的输出从代码重定向到Jupyter Notebook。
我已经找到了可以生成并执行.ipynb文件的nbformat和nbconvert库,因此我只想运行“%run script.py”命令。
这是我要运行的脚本:
<body>
<div class="container"></div>
<div class="full even">
<div class="left">
<div class="content">
Edge
</div>
</div>
<div class="right">
<div class="content">
Edge
</div>
</div>
</div>
<div class="full uneven">
<div class="left">
<div class="content">
Edge
</div>
</div>
<div class="right">
<div class="content">
Edge
</div>
</div>
</div>
</body>
生成.ipynb:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.exp(x)
x = np.linspace(-1, 3, 100)
print(x)
plt.plot(x, f(x))
执行.ipynb:
import nbformat as nbf
nb = nbf.v4.new_notebook()
code = """%run -i temp.py"""
nb['cells'] = [nbf.v4.new_code_cell(code)]
fname = 'test.ipynb'
with open(fname, 'w') as f:
nbf.write(nb, f)
所有文本输出均已生成,但不幸的是,此处未显示图形。这是.ipynb文件:
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors import CellExecutionError
with open("test.ipynb") as f:
nb = nbformat.read(f, as_version=4)
ep = ExecutePreprocessor(timeout=6000, kernel_name='python3')
out = ep.preprocess(nb, {'metadata': {'path': '.'}})
with open('executed_notebook.ipynb', mode='wt') as f:
nbformat.write(nb, f)