从InteractiveShell获取jupyter notebooklike输出。运行\u cell()命令

2024-03-29 04:47:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我在本地环境中有一个对象,我正在尝试运行源自jupyter笔记本的代码。代码需要访问此对象。下面是一个mwe。#(当前)方法的输出是pandas数据帧,而jupyter单元格的输出将是此数据帧的html视图(请参见#(所需))。是否有办法通过上述方法(电流)获得以下输出(所需)

from IPython.core.interactiveshell import InteractiveShell
import pandas as pd
import nbconvert, nbformat

#(current)
shell=InteractiveShell.instance()
shell.user_ns["importantElement"]=[12, 24, 43, 12]
output = shell.run_cell("a=pd.DataFrame({'a':importantElement})\na")
print(f"current output: {output.result}")

#(desired)
ep=nbconvert.preprocessors.ExecutePreprocessor()
ep.km=ep.kernel_manager_class()
ep.km.start_kernel()
ep.kc=ep.km.client()
ep.kc.start_channels()
ep.kc.wait_for_ready(timeout=500)

cell =nbformat.v4.new_code_cell("import pandas as pd\na=pd.DataFrame({'a':[12, 24, 43, 12]})\na")
ep.preprocess_cell(cell,"",1)
print(f"desired output: {cell.outputs}")
ep.kc.stop_channels()
ep.km.shutdown_kernel()

这只是一个例子。我的目标比这个清单更详细。此外,它还需要处理各种输出(数据帧、图形、绘图图形等)。如果有一种方法可以与jupyter内核共享局部变量,那么这也可以解决我的问题(没有pickle,最好没有对文件系统的写入)


Tags: 数据对象方法importpandasoutputcelljupyter