正确使用异步

Proper use of async

我有一个不需要异步的 main 函数,但是这个函数调用了其他几个确实需要异步的函数。

什么是更好的做法:使 main 异步并在 if __name__ ... 中调用 asyncio.run(main()) 还是不使 main 异步更好(它有等待时无事可做)并为从 main?

进行的每个异步函数调用调用 asyncio.run()

换句话说,是这样的:

async def func1():
    await something

async def func2():
    await something

async def main():
    x = input()
    if x == "y":
        await func1()
    else:
        await func2()

if __name__ == "__main__":
    asyncio.run(main())

或者这样:

async def func1():
    await something

async def func2():
    await something

def main():
    x = input()
    if x == "y":
        asyncio.run(func1())
    else:
        asyncio.run(func2())

if __name__ == "__main__":
    main()

如Pythondocs所述

The asyncio.run() function to run the top-level entry point “main()” function (see the above example.)

主要是因为:

This function cannot be called when another asyncio event loop is running in the same thread.

因此,您使用 asyncio.run(main()) 的第一个示例更 Pythonic 并且应该使用