I have a function called from an async
function without await
, and my function needs to call async
functions. I can do this with asyncio.get_running_loop().create_task(sleep())
but the run_until_complete
at the top level doesn’t run until the new task is complete.
How do I get the event loop to run until the new task is complete?
I can’t make my function async
because it’s not called with await
.
I can’t change future
or sleep
. I’m only in control of in_control
.
JavaScript
x
20
20
1
import asyncio
2
3
4
def in_control(sleep):
5
"""
6
How do I get this to run until complete?
7
"""
8
return asyncio.get_running_loop().create_task(sleep())
9
10
11
async def future():
12
async def sleep():
13
await asyncio.sleep(10)
14
print('ok')
15
16
in_control(sleep)
17
18
19
asyncio.get_event_loop().run_until_complete(future())
20
Advertisement
Answer
It appears that the package nest_asyncio
will help you out here. I’ve also included in the example fetching the return value of the task.
JavaScript
1
28
28
1
import asyncio
2
import nest_asyncio
3
4
5
def in_control(sleep):
6
print("In control")
7
nest_asyncio.apply()
8
loop = asyncio.get_running_loop()
9
task = loop.create_task(sleep())
10
loop.run_until_complete(task)
11
print(task.result())
12
return
13
14
15
async def future():
16
async def sleep():
17
for timer in range(10):
18
print(timer)
19
await asyncio.sleep(1)
20
print("Sleep finished")
21
return "Sleep return"
22
23
in_control(sleep)
24
print("Out of control")
25
26
27
asyncio.get_event_loop().run_until_complete(future())
28
Result:
JavaScript
1
16
16
1
In control
2
0
3
1
4
2
5
3
6
4
7
5
8
6
9
7
10
8
11
9
12
Sleep finished
13
Sleep return
14
Out of control
15
[Finished in 10.2s]
16