“RuntimeError: This event loop is already running”; asyncio 报错
发布时间:2019-06-20T09:11:22:手机请访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# -*- coding: utf-8 -*- import asyncio from datetime import datetime async def add(a, b): await asyncio.sleep(1) return a + b async def master_thread(loop): print("{} master: 1+2={}".format(datetime.now(), await add(1, 2))) def slave_thread(loop): # 注意:这不是 coroutine 函数 import time time.sleep(2) f = asyncio.run_coroutine_threadsafe(add(1, 2), loop) print("{} slave: 1+2={}".format(datetime.now(), f.result())) async def main(loop): await asyncio.gather( master_thread(loop), # 线程池内执行 loop.run_in_executor(None, slave_thread, loop), ) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main(loop)) loop.close() |

如何解决呢?
安装 nest_asyncio 模块
1 2 |
pip install nest_asyncio |
使用
1 2 3 4 5 |
import asyncio import nest_asyncio nest_asyncio.apply() from datetime import datetime |
