Created
June 26, 2019 17:53
-
-
Save ktlim/8b30bfbe8645583d3427718f96054974 to your computer and use it in GitHub Desktop.
Log to Jupyter widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ipywidgets as widgets | |
import os | |
import sys | |
import threading | |
class LogWidget: | |
def __init__(self): | |
layout = { | |
'width': '100%', | |
'height': '160px', | |
'border': '1px solid black' | |
} | |
self.out = widgets.Output(layout=layout) | |
self.saved_handle = os.dup(1) | |
pipe_read, pipe_write = os.pipe() | |
os.dup2(pipe_write, 1) | |
os.close(pipe_write) | |
def consumer_thread(f, widget): | |
while True: | |
buf = os.read(f, 1024) | |
if not buf: | |
break | |
with widget: | |
print(buf.decode("utf-8", "strict")) | |
os.close(f) | |
return | |
self.thread = threading.Thread(target=consumer_thread, args=(pipe_read, self.out)) | |
self.thread.start() | |
display(self.out) | |
def stop(self): | |
os.dup2(self.saved_handle, 1) | |
os.close(self.saved_handle) | |
self.thread.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment