简体   繁体   中英

How to call an async python function from a non async function

I have a Python function that must be synchronous (non async) that needs to call an async function. Any way of doing it?

Motivation: async foo() is provided by a communication package and bar() is a callback of a GUI framework so I don't have control over their synchronicity but need to bridge the gap, having bar calling foo and using its returned value.

async def foo():
   return 'xyz'


def bar():
   value = ... foo()

I'm gonna leave my other answer up for posterity (for now) but I looked at the docs again and it turns out that (1) get_event_loop will be deprecated soon and just alias get_running_loop which would result in a RuntimeError , and (2) just using asyncio.run directly does the same thing much more easily:

import asyncio

async def foo():
    return 'xyz'

def bar():
    xyz = asyncio.run(foo())
    print(xyz)

You can use the event loop's run_until_complete method to run a coroutine synchronously:

import asyncio

async def foo():
    return 'xyz'


def bar():
    loop = asyncio.get_event_loop()
    xyz = loop.run_until_complete(foo())
    print(xyz)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM