0
async def func1():
    print(f'{datetime.now().time()} func1 start')
    await asyncio.sleep(1)
    print(f'{datetime.now().time()} func1 over')


async def func21():
    print(f'{datetime.now().time()} func21 start')
    await asyncio.sleep(1)
    print(f'{datetime.now().time()} func21 over')


def func2():
    print(f'{datetime.now().time()} func2 start')
    time.sleep(1)

    asyncio.run_coroutine_threadsafe(func21(), asyncio.get_event_loop())
    print(f'{datetime.now().time()} func2 over')


if __name__ == '__main__':
    for i in range(3):
        func2()
        asyncio.run(func1())

As seen, I want to call async func21() in sync func2(), but it produces RuntimeError when running. So is it possible to do call async func21() in sync func2()?If yes, so how would that be?

f1msch
  • 509
  • 2
  • 12
  • 1
    In many cases, what you are asking for can be done by running an event loop in a secondary thread and executing the async function there. See https://stackoverflow.com/questions/70231451/wrapping-python-async-for-synchronous-execution/70254610#70254610 – Paul Cornelius Aug 17 '22 at 22:05

1 Answers1

0

You can't run async function inside sync function (unless you run the whole event loop there). It's the intentional design decision, because it's important to know where the code can return control to an event loop to avoid concurrency problems.

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159