Skip to content

Instantly share code, notes, and snippets.

@ktlim
Created June 26, 2019 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktlim/8b30bfbe8645583d3427718f96054974 to your computer and use it in GitHub Desktop.
Save ktlim/8b30bfbe8645583d3427718f96054974 to your computer and use it in GitHub Desktop.
Log to Jupyter widget
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