我已阅读有关
%%capture cap
的文档。它仅适用于文本表示。我希望它存储显示在单元格输出中的所有内容;图像、表格,甚至 html 元素。
然后我可以将其加载到另一个具有相同输出的单元格中:
%%capture cap
import matplotlib.pyplot as plt
# Data
x = [1, 2]
y = [3, 4]
# Create a simple plot
plt.plot(x, y)
# Add labels to the axes
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# Add a title to the plot
plt.title('Simple Plot Example')
# Show the plot
plt.show()
# Save the captured output to a text file
with open('stdout.txt', 'w') as file:
file.write(cap.stdout)
#@title Reloading CELL_A output
with open('stdout.txt', 'r') as file:
cell_a_out = file.read()
display(cell_a_out)
它应该显示matplotlib图像。我知道 matplotlib 提供了保存图形方法来保存图像。但我希望保存单元格输出中显示的所有内容,而不仅仅是图像。因此,如果单元格返回 pandas 和 matplotlib 图像的输出表,则可以将其存储在单个文件中。
只需在单元格 A 中通过 id
output-area
和 innerHTML
获取元素,然后简单地显示 HTML 字符串
from google.colab import output
# Data
x = [1, 2]
y = [3, 4]
# Create a simple plot
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Plot Example')
plt.show()
# Execute JavaScript code and get `output-area`
output_from_cell_a = output.eval_js('document.getElementById("output-area").innerHTML;')
print(output_from_cell_a)
print(type(output_from_cell_a))
from IPython.display import HTML
# Redisplay output from cell A
display(HTML(output_from_cell_a))
正如你所猜测的,你可以使用
output_from_cell_a
将 html 变量open(output_from_cell_a.html)
的字符串存储到文件中,并且可以随时加载。