Python Asyncio: RuntimeError: 这个事件循环已经 运行

Python Asyncio: RuntimeEror: This eventloop is already running

我正在开发 ayncio 模块,但在 终止程序 中遇到问题。我在终端 运行ning 我的程序并且 Ctrl + C 无法停止 运行ning program.However,如果我关闭终端并且再次尝试 运行 编程,我遇到了这个问题:

INFO:root:In main
ERROR:root:This event loop is already running

下面是我的示例代码,供大家理解。

# all_tasks.py

import asyncio
import logging
# module imports
import settings

#configure logging into a file
logging.basicConfig(filename=settings.LOG_FILENAME,level=logging.DEBUG)


class AsyncTest(object):

    async def taskOne(self):
        while True:
            print("Task One") # Print is just an example, I am doing lot of stuff inside.
            await asyncio.sleep(60)

    async def taskTwo(self):
        while True:
            print("Task Two") # Print is just an example, I am doing lot of stuff inside.
            await asyncio.sleep(60) 

    async def main(self):
        try:
            loop = asyncio.get_event_loop()
                tasks = [
                        asyncio.ensure_future(self.taskOne()),
                        asyncio.ensure_future(self.taskTwo()),
                        ]
            loop.run_until_complete(asyncio.wait(tasks))
        except RuntimeError as error:
            logging.info("In main")
            logging.error(error)

if __name__ == '__main__':
    asynctest = AsyncTest()
    asyncio.run(asynctest.main())

Config: Windows 10, python 3.7.0

File Name: all_tasks.py

Command: python all_tasks.py

非常感谢任何帮助。 谢谢

asyncio.run 创建并 运行s 事件循环。您不应该创建 运行 一个,尤其是在协程中(用 async def 定义的函数)。在协同程序中,你应该只 await 做某事。

相应地修改代码:

# ...

    async def main(self):
        tasks = [
            asyncio.ensure_future(self.taskOne()),
            asyncio.ensure_future(self.taskTwo()),
        ]
        await asyncio.wait(tasks)

if __name__ == '__main__':
    asynctest = AsyncTest()
    asyncio.run(asynctest.main())

它会起作用。