首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在jupyter notebook中读取其他单元格

如何在jupyter notebook中读取其他单元格
EN

Stack Overflow用户
提问于 2021-01-04 20:01:23
回答 1查看 108关注 0票数 0

我正在尝试为jupyter notebook编写一个神奇的函数,它可以让我在notebook中直接看到manim的输出。

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

我的问题是,假设我在其他单元格(甚至import语句)中声明了一些其他变量,并在调用我的魔术函数的单元格中使用它们。如何才能将来自其他单元格的那些变量(或者基本上是代码)保存在同一个临时.py文件中,这样我就不会收到错误?或者任何其他可以实现的方式?希望下面的截图能更好地解释我想问的问题。

下面是我使用的代码:

代码语言:javascript
复制
# 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)
EN

回答 1

Stack Overflow用户

发布于 2021-03-03 00:00:12

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65562394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档