如何读取jupyter笔记本中的其他单元格

2024-10-03 15:22:01 发布

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

我正在尝试为jupyter笔记本编写一个神奇的函数,它可以让我直接在笔记本中看到^{}的输出

为了实现这一点,我基本上将单元格的内容保存到一个临时的.py文件中,然后使用临时的.py文件在子进程中调用manimce命令,并检查输出以查找创建的视频/gif的路径

我的问题是,假设我在其他单元格(甚至是import语句)中声明了一些其他变量,并且我在调用magic函数的单元格中使用它们。如何将其他单元格中的变量(或基本上是代码)保存在同一个临时.py文件中,以避免出错?或者其他可以实现的方法?希望下面的截图能更好地解释我想问的问题

jupyter-notebook-screenshot

以下是我使用的代码:

# manimce_magic.py
from IPython.core.display import display, HTML
from IPython.core.magic import Magics, magics_class, line_magic, cell_magic, line_cell_magic
from IPython.core.magic import needs_local_scope
from pathlib import Path
from subprocess import Popen, PIPE
from tempfile import NamedTemporaryFile
import IPython.display
import os
import re

def find_path(output_string):
    output_string = output_string.decode('utf-8')
    output_string = re.sub(' ', '', ''.join(output_string.split('\n')))
    if m := re.search('(?<=Filereadyat).+(?=INFO)', output_string):
        return m.group(0)

@magics_class
class ManimceMagic(Magics):
    @needs_local_scope
    @cell_magic
    def manimce(self, line, cell, **kwargs):
        manimce_args = line.split()
        f = NamedTemporaryFile('r+', suffix='.py', delete=False)
        try:
            f.write(cell)
            f.close()

            args = ['manimce', f.name, *manimce_args]
            p = Popen(args, stdout=PIPE, stdin=PIPE, stderr=PIPE)
            output, err = p.communicate()
            path = find_path(output)
            display(IPython.display.Code(output.decode('utf-8'), language='python3'))
            display(p.returncode)
        finally:
            os.remove(f.name)

        if path:
            path = Path(path)
            relative_path = path.relative_to(Path.cwd())

            if '-i' in manimce_args:
                return IPython.display.Image(relative_path, width=854, height=480)
            else:
                return IPython.display.Video(relative_path, width=854, height=480, html_attributes='controls loop autoplay')

def load_ipython_extension(ipython):
    ipython.register_magics(ManimceMagic)


Tags: pathfrompyimportoutputstringmagicipython
1条回答
网友
1楼 · 发布于 2024-10-03 15:22:01

我无法回答你的具体问题,但这或许会有所帮助。我相信当前版本的manim已经有了一个manim魔法命令。我试过了,似乎效果不错。我让它工作,我首先运行import jupyter_manim,然后在一个新的单元格中,我编写我的程序,从神奇的命令%%manim TestClass -p -ql开始,其中TestClass是我正在构建的动画的名称。manim输出就出现在Jupyter笔记本中

相关问题 更多 >