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?

1
  • 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 stackoverflow.com/questions/70231451/… Commented Aug 17, 2022 at 22:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.