我正在研究ayncio模块并在终止程序时遇到问题。我在终端中运行我的程序,Ctrl + C无法停止正在运行的程序。但是,如果我关闭终端并尝试再次运行程序,我会遇到这个问题:
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
创建并运行事件循环。你不应该创建和运行一个,特别是在一个协程(用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())
它会工作的。