简体   繁体   English

我可以将 output 打印到 jupyter 笔记本中的另一个单元格吗?

[英]Can I print output to another cell in a jupyter notebook?

Let's assume there is a jupyter notebook that has two cells.假设有一个包含两个单元格的 jupyter notebook。 In the second cell, we generate some output, eg by running print('foo') .在第二个单元格中,我们生成一些 output,例如通过运行print('foo') Is there a way to change that print command in such a way that the output will be displayed as output of the first cell?有没有办法更改该打印命令,使第一个单元格的 output 显示为 output?

Why?为什么? In a typical data analysis workflow, I access several data sources somewhere in the notebook.在典型的数据分析工作流程中,我访问笔记本中某处的多个数据源。 It would be nice if I could extend my access_data method in such a way that all sources that I have used are listed in the first cell.如果我可以扩展我的access_data方法,使我使用过的所有源都列在第一个单元格中,那就太好了。

First example:第一个例子:

# cell 1
from IPython.display import display
import random as rd
import pandas as pd
import numpy as np
import matplotlib.pylab as plt

# cell 2
h = display(display_id='my-display')

# cell 3
h.display(None)
# ==> output is updated at each h.update() command in cells below

# cell 4
s = ''.join(rd.choices('abcedfghijklmn', k=5))
h.update(s)

# cell 5
a, b, c, d = rd.choices(range(10), k=4)
arr = np.array([[a,b,c,d], [d,c,b,a]])
h.update(arr)

# cell 6
a, b, c, d = rd.choices(range(10), k=4)
df = pd.DataFrame(data=[[a,b],[c,d]], columns=['A', 'B'])
h.update(df)

# cell 7
a, b, c, d = rd.choices(range(10), k=4)
df = pd.DataFrame(data=[[a,b],[c,d]], columns=['a', 'b'])
ax = df.plot();
fig = ax.get_figure()
h.update(fig)
plt.close()

# cell 8
fig, ax = plt.subplots()
a,b,c,d = rd.choices(range(10), k=4)
ax.plot([a,b,c,d]);
h.update(fig)
plt.close()

Second example with helper class and some mime types management:辅助类和一些 mime 类型管理的第二个示例:

# cell 1
from IPython.display import display

import random as rd
import numpy as np
import pandas as pd
import matplotlib.pylab as plt

# cell 2
class Output:
    """
    Helper class
    """
    def __init__(self, name='my-display'):
        self.h = display(display_id=name)
        self.content = ''
        self.mime_type = None
        self.dic_kind = {
            'text': 'text/plain',
            'markdown': 'text/markdown',
            'html': 'text/html',
        }

    def display(self):
        self.h.display({'text/plain': ''}, raw=True)

    def _build_obj(self, content, kind, append, new_line):
        self.mime_type = self.dic_kind.get(kind)
        if not self.mime_type:
            return content, False
        if append:
            sep = '\n' if new_line else ''
            self.content = self.content + sep + content
        else:
            self.content = content
        return {self.mime_type: self.content}, True

    def update(self, content, kind=None, append=False, new_line=True):
        obj, raw = self._build_obj(content, kind, append, new_line)
        self.h.update(obj, raw=raw)


# cell 3
out = Output(name='my-display-2')
out.display()
# ==> output is updated at each h.update() command in cells below

# cell 4
s = ''.join(rd.choices('abcedfghijklmn', k=5))
out.update(s, kind='text', append=False)

# cell 5
a, b = rd.choices(range(10), k=2)
s = f'''\
# Heading one {a}

This is a sample  {b}

* a
* list
'''
out.update(s, kind='markdown', append=True)

# cell 6
a, b = rd.choices(range(10), k=2)
s = f'''\
<h3>My Title {a}</h3>
<p>My paragraph {b}</p>
'''
out.update(s, kind='html')

# cell 7
a, b, c, d = rd.choices(range(10), k=4)
arr = np.array([[a,b,c,d], [d,c,b,a]])
out.update(arr)

# cell 8
a, b, c, d = rd.choices(range(10), k=4)
df = pd.DataFrame(data=[[a,b],[c,d]], columns=['A', 'B'])
out.update(df)

# cell 9
a, b, c, d = rd.choices(range(10), k=4)
df = pd.DataFrame(data=[[a,b],[c,d]], columns=['a', 'b'])
ax = df.plot();
fig = ax.get_figure()
out.update(fig)
plt.close()

# cell 10
fig, ax = plt.subplots()
a,b,c,d = rd.choices(range(10), k=4)
ax.plot([a,b,c,d]);
out.update(fig)
plt.close()

Yes.是的。 Using %%capture var magic使用%%capture var魔法

+Info on https://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-capture +信息https://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-capture

在此处输入图像描述

%%capture captured
# First cell
x="""Let's assume there is a jupyter notebook that has two cells. In the second cell, we generate some output, e.g. by running print('foo'). Is there a way to change that print command in such a way that the output will be displayed as output of the first cell?"""
print(x)
y=[1,2]*3
print(y)
a=list(range(10))
print(a)
m=f'There are lots of ways: {a}'
m


# second cell
print(captured)

Note: m Is not captured as it wasn't 'output'.注意: m未被捕获,因为它不是“输出”。 (I added it intentionally) (我是故意加的)

Tested on JupyterLab / Jupyter Notebook with Python 3.7使用 Python 3.7 在 JupyterLab / Jupyter Notebook 上测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Jupyter Notebook 不会将日志打印到输出单元格 - Jupyter notebook does not print logs to the output cell 将jupyter notebook单元格的输出打印到文件 - Print the output from jupyter notebook cell to a file 我可以在 Jupyter 笔记本中运行一个单元,而另一个单元正在运行吗? - Can I run a cell in a Jupyter notebook while another cell is running? 如何将 Jupyter 笔记本中单元格的输出复制到剪贴板? - How can I copy to the clipboard the output of a cell in a Jupyter notebook? 如何打印像jupyter笔记本的默认单元格输出 - How to print like jupyter notebook's default cell output 如何从文件中的 Jupyter Notebook 单元格打印多个输出? - How can I print multiple outputs from a Jupyter Notebook cell in a file? 当我将 Jupyter Notebook 转换为 PDF 时,我可以漂亮地打印 linearmodels.panel.results.compare() 的 output 吗? - Can I pretty print the output of linearmodels.panel.results.compare() when I convert a Jupyter Notebook to PDF? 在 Jupyter 笔记本 Markdown 单元格 Python 中打印变量 - Print Variable In Jupyter Notebook Markdown Cell Python 在Jupyter笔记本单元中漂亮地打印几个变量 - Pretty print several variables in a Jupyter notebook cell 无法在Jupyter Notebook单元中打印bash变量 - Cannot print bash variables in Jupyter notebook cell
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM