python - asyncio.new_event_loop 创建的事件循环挂起

标签 python python-3.x python-asyncio event-loop python-3.5

下面的代码没有打印任何东西就挂了:

import asyncio

async def foo(loop):
    print('foo')
    loop.stop()

loop = asyncio.new_event_loop()
asyncio.ensure_future(foo(loop))
loop.run_forever()

如果我使用 get_event_loop一切正常。是我做错了什么还是我偶然发现了错误?

我正在使用 Python 3.5.1。

最佳答案

asyncio.AbstractEventLoopPolicy.new_event_loop documentation说:

If there’s need to set this loop as the event loop for the current context, set_event_loop() must be called explicitly.


import asyncio

async def foo(loop):
    print('foo')
    loop.stop()

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) # <----
asyncio.ensure_future(foo(loop))
loop.run_forever()

关于python - asyncio.new_event_loop 创建的事件循环挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470856/

相关文章:

python - 我怎样才能去掉 ttk 打印表格中的 ], [ 和 ' 标志

python - Scikit DBSCAN eps 和 min_sample 值确定

javascript - 在 Linux 上部署 Javascript 应用程序的最简单方法

python - 使用请求选择和上传 pdf 文件时遇到问题

python - 在 Python 3.8 中修补异步对象

python - 在此异步设置中,我在哪里捕获 KeyboardInterrupt 异常

python - python asyncio call_soon_threadsafe 真的是线程安全的吗?

python - 当 cp 没有时,为什么 shutil.copy() 会引发权限异常?

python - 根据列表元素内的值对列表进行排序

python - 如何在python中编写n次函数