@@ -294,6 +294,34 @@ def __init__(self, nb, km=None, **kw):
294
294
self .km = km
295
295
self .reset_execution_trackers ()
296
296
297
+ def run_blocking (self , coro ):
298
+ """Runs a coroutine and blocks until it has executed.
299
+
300
+ An event loop is created if no one already exists. If an event loop is
301
+ already running, this event loop execution is nested into the already
302
+ running one if `nest_asyncio` is set to True.
303
+
304
+ Parameters
305
+ ----------
306
+ coro : coroutine
307
+ The coroutine to be executed.
308
+
309
+ Returns
310
+ -------
311
+ result :
312
+ Whatever the coroutine returns.
313
+ """
314
+ try :
315
+ loop = asyncio .get_event_loop ()
316
+ except RuntimeError :
317
+ loop = asyncio .new_event_loop ()
318
+ asyncio .set_event_loop (loop )
319
+ if self .nest_asyncio :
320
+ import nest_asyncio
321
+ nest_asyncio .apply (loop )
322
+ result = loop .run_until_complete (coro )
323
+ return result
324
+
297
325
def reset_execution_trackers (self ):
298
326
"""Resets any per-execution trackers.
299
327
"""
@@ -380,6 +408,9 @@ async def setup_kernel(self, **kwargs):
380
408
self .kc .stop_channels ()
381
409
self .kc = None
382
410
411
+ def execute (self , ** kwargs ):
412
+ return self .run_blocking (self .async_execute (** kwargs ))
413
+
383
414
async def async_execute (self , ** kwargs ):
384
415
"""
385
416
Executes each code cell.
@@ -551,6 +582,11 @@ def _check_raise_for_error(self, cell, exec_reply):
551
582
if (exec_reply is not None ) and exec_reply ['content' ]['status' ] == 'error' :
552
583
raise CellExecutionError .from_cell_and_msg (cell , exec_reply ['content' ])
553
584
585
+ def execute_cell (self , cell , cell_index , execution_count = None , store_history = True ):
586
+ return self .run_blocking (
587
+ self .async_execute_cell (cell , cell_index , execution_count , store_history )
588
+ )
589
+
554
590
async def async_execute_cell (self , cell , cell_index , execution_count = None , store_history = True ):
555
591
"""
556
592
Executes a single code cell.
@@ -750,24 +786,6 @@ def _get_buffer_data(self, msg):
750
786
return encoded_buffers
751
787
752
788
753
- def make_blocking (async_method ):
754
- def blocking_method (self , * args , ** kwargs ):
755
- try :
756
- loop = asyncio .get_event_loop ()
757
- except RuntimeError :
758
- loop = asyncio .new_event_loop ()
759
- asyncio .set_event_loop (loop )
760
- if self .nest_asyncio :
761
- import nest_asyncio
762
- nest_asyncio .apply (loop )
763
- return loop .run_until_complete (async_method (self , * args , ** kwargs ))
764
- return blocking_method
765
-
766
-
767
- NotebookClient .execute = make_blocking (NotebookClient .async_execute )
768
- NotebookClient .execute_cell = make_blocking (NotebookClient .async_execute_cell )
769
-
770
-
771
789
def execute (nb , cwd = None , km = None , ** kwargs ):
772
790
"""Execute a notebook's code, updating outputs within the notebook object.
773
791
0 commit comments