4
4
# Distributed under the terms of the Modified BSD License.
5
5
6
6
import asyncio
7
+ import sys
7
8
import inspect
8
9
9
10
11
+ def check_ipython ():
12
+ # original from vaex/asyncio.py
13
+ IPython = sys .modules .get ('IPython' )
14
+ if IPython :
15
+ IPython_version = tuple (map (int , IPython .__version__ .split ('.' )))
16
+ if IPython_version < (7 , 0 , 0 ):
17
+ raise RuntimeError (f'You are using IPython { IPython .__version__ } while we require'
18
+ '7.0.0+, please update IPython' )
19
+
20
+
21
+ def check_patch_tornado ():
22
+ """If tornado is imported, add the patched asyncio.Future to its tuple of acceptable Futures"""
23
+ # original from vaex/asyncio.py
24
+ if 'tornado' in sys .modules :
25
+ import tornado .concurrent
26
+ if asyncio .Future not in tornado .concurrent .FUTURES :
27
+ tornado .concurrent .FUTURES = tornado .concurrent .FUTURES + (asyncio .Future , )
28
+
29
+
30
+ def just_run (coro ):
31
+ """Make the coroutine run, even if there is an event loop running (using nest_asyncio)"""
32
+ # original from vaex/asyncio.py
33
+ loop = asyncio ._get_running_loop ()
34
+ if loop is None :
35
+ had_running_loop = False
36
+ try :
37
+ loop = asyncio .get_event_loop ()
38
+ except RuntimeError :
39
+ # we can still get 'There is no current event loop in ...'
40
+ loop = asyncio .new_event_loop ()
41
+ asyncio .set_event_loop (loop )
42
+ else :
43
+ had_running_loop = True
44
+ if had_running_loop :
45
+ # if there is a running loop, we patch using nest_asyncio
46
+ # to have reentrant event loops
47
+ check_ipython ()
48
+ import nest_asyncio
49
+ nest_asyncio .apply ()
50
+ check_patch_tornado ()
51
+ return loop .run_until_complete (coro )
52
+
53
+
10
54
def run_sync (coro ):
11
55
"""Runs a coroutine and blocks until it has executed.
12
56
@@ -24,26 +68,8 @@ def run_sync(coro):
24
68
result :
25
69
Whatever the coroutine returns.
26
70
"""
27
- def wrapped (self , * args , ** kwargs ):
28
- try :
29
- loop = asyncio .get_event_loop ()
30
- except RuntimeError :
31
- loop = asyncio .new_event_loop ()
32
- asyncio .set_event_loop (loop )
33
- if self .nest_asyncio :
34
- import nest_asyncio
35
- nest_asyncio .apply (loop )
36
- try :
37
- result = loop .run_until_complete (coro (self , * args , ** kwargs ))
38
- except RuntimeError as e :
39
- if str (e ) == 'This event loop is already running' :
40
- raise RuntimeError (
41
- 'You are trying to run nbclient in an environment where an '
42
- 'event loop is already running. Please pass `nest_asyncio=True` in '
43
- '`NotebookClient.execute` and such methods.'
44
- ) from e
45
- raise
46
- return result
71
+ def wrapped (* args , ** kwargs ):
72
+ return just_run (coro (* args , ** kwargs ))
47
73
wrapped .__doc__ = coro .__doc__
48
74
return wrapped
49
75
0 commit comments