Heim  >  Fragen und Antworten  >  Hauptteil

Wie erstellt man eine Funktion in Python-Code, die IPython-Rich-Ausgabe (HTML-Format) als Ausgabe verwendet?

<p>So erstellen Sie eine Funktion namens <code>foo()</code> <pre class="brush:php;toolbar:false;">pycode = ''' aus matplotlib Pyplot als plt importieren plt.plot([1, 2, 3]) plt.show() ''' out = foo(pycode)</pre> <p>Wobei<code>out</code> die Rich-Text-HTML-Ausgabe ist, die von ipython oder jupyter notebook ausgegeben wird</p> <p>Gibt es in ipython eine integrierte Funktion, die dies erreichen kann? Ich schätze, das sollte es geben, aber ich kann es bei Google nicht finden. </p> <p>BEARBEITEN: Ich möchte, dass diese Funktion in meinem Python-Skript vorhanden ist, nicht beim Ausführen der ipython-Shell. </p> <p> EDIT: Was ich tun möchte, ist im Grunde etwas Ähnliches wie eine Jupyter-Notebook-Zelle. Ich gebe ihr den Code und sie gibt die umfangreiche Ausgabe (wahrscheinlich in HTML) auf visuelle Weise zurück, genau wie die Jupyter-Notebook-Zelle. Dasselbe Format. </p>
P粉713846879P粉713846879415 Tage vor625

Antworte allen(1)Ich werde antworten

  • P粉486138196

    P粉4861381962023-09-01 16:15:29

    我认为你正在寻找Python的exec()方法?

    在安装了matplotlib的JupyterLab中,你可以在一个单元格中运行以下代码,并在其下方看到输出:

    pycode = '''
    from matplotlib import pyplot as plt
    plt.plot([1, 2, 3])
    plt.show()
    '''
    out = exec(pycode)
    

    请记住,一般情况下不建议使用exec()和相关的eval()。它们的使用可能会使其他人甚至你自己无意中执行你不想运行的代码,从而引发严重问题。如果你使用正确的方法,通常不需要使用它们,可以参考这里。(现在似乎甚至可以使用基于WebAssembly的Python来执行,参见PyScript: is it possible to execute an uploaded Python script?。)


    根据第一个评论的回应更新:

    如此编写的话,尽管代码能够绘制图形,但out并没有收集任何内容,因为exec(pycode)恰好在最后一行。可以通过使用IPython的捕获工具来收集RichOutput。而且,由于它是通过导入实现的,如果你在Python中也安装了Jupyter生态系统,它应该也能够工作。换句话说,尽管我在notebook中演示它,你可以编写一个函数来使用return captured.outputs[0],它将返回绘图的RichOutput。

    这个notebook中详细阐述了底层的原理。

    请注意,由于我处理的是RichOutput和生成图像,你还需要查看其中的引用。其中还有很多内容我没有涉及。


    创建一个简单的函数,不使用exec()

    这个示例notebook中,可以看到如何以编程方式创建一个.py文件。通常情况下,你可以通过手动保存文本来在文本编辑器中创建这样的文件,例如将以下内容保存为plot_func.py

    def my_plot_func():
        from matplotlib import pyplot as plt
        plt.plot([1, 2, 3])
        plt.savefig('my_plot_via_func.png')
    

    然后导入并运行它。在这个过程中,还会保存一个图像文件。在notebook中,该图像文件my_plot_via_func.png会被显示出来。

    这只是一个简单的版本。导入和执行函数的过程在纯Python中的终端或其他地方也可以工作,直到显示图像文件。如果你以图形对象(图形)的形式返回绘图结果,你需要一种显示的方式。在Jupyter中可以工作,但在纯Python中不行。

    我添加了这个部分,因为我仍然不清楚你想要做什么。我还有一个更高级的版本,可以使用特殊组织的Pandas数据帧来生成专门的绘图。要尝试,请点击这里,然后点击launch binder,并按照会话开始时出现的示例notebook进行操作。也许这能帮助你更好地表达你的需求。特别是因为它将类似于这个绘图脚本中的所有硬编码的东西泛化,使其成为一个可以调用的命令行脚本或函数。你将看到我在下面的评论中所说的必要基础设施。命令行脚本也可以在纯Python中运行。你会看到我在notebook中通常使用%run,因为它更全面;然而,在notebook中,如果你可以牺牲更好的输出处理并且不需要在notebook命名空间中运行脚本,那么你通常可以将!python替换为%run,就像%run -i允许的那样。

    关于使用matplotlib绘图生成返回特定绘图的代码的示例,可以参见这里


    生成HTML

    原始问题是关于HTML的,我在这个主要示例notebook的底部添加了一个生成HTML的部分,这是对第一个评论的回应。实际上,这篇帖子“将matplotlib图形嵌入iPython HTML”可能已经涵盖了原始问题的大部分内容?

    Antwort
    0
  • StornierenAntwort