ipython / ipython

Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.
https://ipython.readthedocs.org
BSD 3-Clause "New" or "Revised" License
16.27k stars 4.43k forks source link

How do I capture stdout as variables ? #13066

Closed helloooideeeeea closed 3 years ago

helloooideeeeea commented 3 years ago

I want to capture stdout as variable with IPython. but, following code does not work.

import sys
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from IPython.core.displayhook import CapturingDisplayHook
from IPython.utils.capture import CapturedIO

shell = TerminalInteractiveShell.instance()

block='''
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from pandas import Series, DataFrame
from sklearn.datasets import load_boston

boston = load_boston()
df_boston = DataFrame(boston.data, columns=boston.feature_names)
x_org, yt = boston.data, boston.target
feature_names = boston.feature_names
x_data = x_org[:,feature_names == 'RM']
x = np.insert(x_data, 0, 1.0, axis=1)
plt.scatter(x[:,1], yt, s=10, c='b')
plt.xlabel('ROOM', fontsize=14)
plt.ylabel('PRICE', fontsize=14)
plt.show()
'''

hook = CapturingDisplayHook(shell)
captured = CapturedIO(sys.stdout, sys.stderr, hook.outputs)
a = shell.run_cell(block)
print(captured.outputs)

Terminal Output

<Figure size 432x288 with 1 Axes>
[] <- Why ??

I want to capture Figure Class like following (output to stdout ). <Figure size 432x288 with 1 Axes>

How do I capture Figure class as variable ?

thanks.

MrMino commented 3 years ago

There's nothing in your code that would actually go towards capturing the output. What are you basing this code on?

Why not use the %%capture magic?

helloooideeeeea commented 3 years ago

@MrMino Thanks. Your Answer helped me ! But My question was wrong.

on Matplotlib inline mode, How does JupterNotebook publish graph png image ?.. on jupter kernel sever(ipython), does it exec plt.savefig('x.png') ?..

I close the issue once.

MrMino commented 3 years ago

@helloooideeeeea See https://ipython.readthedocs.io/en/stable/config/integrating.html#rich-display

helloooideeeeea commented 3 years ago

@MrMino Thanks! I got pyplot image data. I might be able to Capture this output to KIVY!

from IPython.terminal.interactiveshell import TerminalInteractiveShell

shell = TerminalInteractiveShell.instance()

from pandas import DataFrame
from matplotlib.collections import PathCollection

formatter = shell.display_formatter.formatters['text/plain']

def dataframe_formatter(object, printer, cycle):
    printer.text('test')

def pyplot_formatter(object, printer, cycle):
    import io
    import base64
    # object.figure.savefig('test.png')
    data = io.BytesIO()
    object.figure.savefig(data)
    base64Text = base64.b64encode(data.getvalue()).decode()
    printer.text(base64Text)

formatter.for_type(DataFrame, dataframe_formatter)
formatter.for_type(PathCollection, pyplot_formatter)

block='''

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from pandas import Series, DataFrame
from sklearn.datasets import load_boston

boston = load_boston()
DataFrame(boston.data, columns=boston.feature_names)
x_org, yt = boston.data, boston.target
feature_names = boston.feature_names
x_data = x_org[:,feature_names == 'RM']
x = np.insert(x_data, 0, 1.0, axis=1)
plt.scatter(x[:,1], yt, s=10, c='b')
'''

a = shell.run_cell(block)

Terminal Output

Out[1]: iVBORw0KGgoAAAANSUhEUgAAAbAAAAEgCAYAAADVKCZpAAAAOXRF....
<Figure size 432x288 with 1 Axes>