【发布时间】:2020-02-14 23:34:26
【问题描述】:
我希望从一个函数中捕获 stdout 输出,这样当第一次调用该函数时,它的输出将正常显示在 iPython notebook 中,但是当它第二次调用时,它的输出将重写之前的输出. (这样之前的输出会被清除,新的输出会显示在同一个地方)
我已经使用输出 ipywidget 实现了我想要的,尽管它也捕获并清除了 stderr。不幸的是,这是不可接受的,因为我需要在程序完成时显示 stderr 输出。
这是我目前拥有的代码的最小(非)工作示例:
import sys
from ipywidgets import widgets
from IPython.display import display, clear_output
# This function is in some library and cannot be changed
def black_box(iter):
print('Some output to stdout {}.'.format(iter)) #This is supposed to be cleared on each function call
sys.stderr.write('Some output to stderr {}.'.format(iter)) #This is NOT supposed to be cleared on each function call
print('Some other output that is not supposed to be cleared.')
output = widgets.Output()
display(output)
with output: # I need this to capture only stdout, not stderr ...
black_box(1)
print('Some other output that is not supposed to be cleared.')
with output:
clear_output() # ... so that this line clears only stdout, not stderr
black_box(2)
输出如下:
Some other output that is not supposed to be cleared.
Some output to stdout 2.
Some output to stderr 2.
Some other output that is not supposed to be cleared.
我希望输出的样子:
Some other output that is not supposed to be cleared.
Some output to stdout 2.
Some output to stderr 1.
Some output to stderr 2.
Some other output that is not supposed to be cleared.
如您所见,stderr 输出也在第二个函数调用中被捕获和清除。有谁知道解决这个问题的任何方法?谢谢。
【问题讨论】:
标签: python-3.x jupyter-lab ipywidgets