In jupyter-lab I have a long running function long_runner()
doing some heavy numeric computation. I would like to be able to stop this function by clicking on an ipywidget button. Interrupting the kernel is not an option since other parts of the GUI should continue working.
Here is a code example with a button which sets a stop flag. This stop flag is used in long_runner
to break out of the loop. When long_runner
is active, the Button seems to be reactive to clicks, but the associated function set_stop_flag
is only executed after long_runner
has finished normally and thus no intermediate stop is possible.
I looked at some examples with asyncio but could not find something fitting this use-case with a heavy-compute function.
How could the desired behavior be acchieved?
from ipywidgets import Button
stop_flag = 0
def set_stop_flag(b):
global stop_flag
print("stop flag activated")
stop_flag = 1
b=Button(description="stop")
b.on_click(set_stop_flag)
display(b)
def long_runner():
x=0
print("starting ...")
for i in range(100000000):
if stop_flag==1:
print("stop=",stop_flag)
break
x += i*i
print("stopping",i)
return(x,i)
print(long_runner())
Here is the program output when the stop-button is clicked during the execution of long-runner
: