我正在使用jupyter笔记本创建一个软件文档(sphinx与nbsphinx)。我想在jupyter笔记本中包含一些.py文件。这些文件应该被加载并显示在一个单元格中(因为它们应该在以后的文档中出现),并且运行它们以产生所需的输出(绘图和文本)。在
我发现不久前有人问过类似的问题: Jupyter: Write a custom magic that modifies the contents of the cell it's in 然而,使用这个答案对我不起作用。在
我不得不做一个小的修改,因为我不想在执行单元后注释掉魔行本身。('\%lmagic\n{}'->;'%lmagic\n{}')
from __future__ import print_function
from IPython.core.magic import Magics, magics_class, line_magic
@magics_class
class MyMagics(Magics):
@line_magic
def lmagic(self, line):
raw_code = 'print("Hello world!")'
# Comment out this line if you actually want to run the code.
self.shell.set_next_input('%lmagic\n{}'.format(raw_code), replace=True)
# Uncomment this line if you want to run the code instead.
self.shell.run_cell(raw_code, store_history=False)
#import time
#time.sleep(2)
ip = get_ipython()
ip.register_magics(MyMagics)
在下一个单元格中执行:
^{pr2}$不会显示任何输出。但是,如果我添加了一个短时间的睡眠(通过取消代码段中的两行注释),我可以观察到它是临时显示的,然后消失了。我假设异步函数调用和呈现起作用。在
测试对象: Jupyter笔记本5.7.8,IPython 7.4.0
有什么办法解决吗?在
朱利安
目前没有回答
相关问题 更多 >
编程相关推荐