- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我知道在 python37 中我们有一个新的 api asyncio.get_running_loop()
,好用,让我们在调用协程的时候不需要显式传递eventloop。
我想知道我们是否可以使用任何方法在 python36 中获得相同的效果?
# which allows us coding conveniently with this api:
import asyncio
async def test():
print("hello world !")
async def main():
loop = asyncio.get_running_loop()
loop.create_task(test())
asyncio.run(main())
最佳答案
在 Python 3.6 中,您可以使用 asyncio.get_event_loop()
达到同等效果。
根据documentation ,相当于调用get_event_loop_policy().get_event_loop()
,这又是 documented从协程调用时返回“当前正在运行的事件循环”。
换句话说,当从协程(或从协程调用的函数)调用时,get_event_loop
之间没有区别。和 get_running_loop
,两者都将返回运行循环。只有在没有循环运行时 get_event_loop()
将继续返回与当前线程关联的循环,而 get_running_loop()
将引发异常。只要你细心调用get_event_loop()
当一个循环实际运行时,它相当于 get_running_loop()
.
请注意 get_event_loop
从协程调用时返回运行循环是 new to Python 3.6 and 3.5.3 .在这些版本之前,get_event_loop
将始终返回与当前线程关联的事件循环,这可能是与实际运行的循环不同的循环。这使得 get_event_loop()
根本上不可靠,这也是旧异步代码会通过 loop
的原因到处争论。更多详情 here .
关于python-3.6 - 如何在 python36 中获取当前正在运行的 EventLoop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56740479/
我是一名优秀的程序员,十分优秀!