Skip to content

Instantly share code, notes, and snippets.

@maartenbreddels
Last active July 28, 2020 14:07
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save maartenbreddels/3378e8257bf0ee18cfcbdacce6e6a77e to your computer and use it in GitHub Desktop.
Save maartenbreddels/3378e8257bf0ee18cfcbdacce6e6a77e to your computer and use it in GitHub Desktop.
IPython snippet for doing work in a thread, and updating a progressbar
import threading
from IPython.display import display
import ipywidgets as widgets
import time
def get_ioloop():
import IPython, zmq
ipython = IPython.get_ipython()
if ipython and hasattr(ipython, 'kernel'):
return zmq.eventloop.ioloop.IOLoop.instance()
ioloop = get_ioloop()
thread_safe = True
def work():
for i in range(10):
def update_progress(i=i):
print "calling from thread", threading.currentThread()
progress.value = (i+1)/10.
print i
time.sleep(0.5)
if thread_safe:
get_ioloop().add_callback(update_progress)
else:
update_progress()
print "we are in thread", threading.currentThread()
thread = threading.Thread(target=work)
progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0, step=0.01)
display(progress)
thread.start()
@SylvainCorlay
Copy link

👍

@the-moog
Copy link

the-moog commented Jan 5, 2020

I've updated this for Python3 and provided an IPython notebook example:
https://gist.github.com/the-moog/94b09b49232731bd2a3cedd24501e23b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment