python 3.5的异步生成器和上下文管理器+
async_generator的Python项目详细描述
异步发生器库
python 3.6添加了async generators。(什么是异步 发电机?Check out my 5-minute lightning talk demo from PyCon 2016.)python 3.7增加了更多内容 使它们可用的工具,如contextlib.asynccontextmanager。
这个库将所有这些都返回到Python3.5。
例如,此代码仅适用于Python3.6+:
asyncdefload_json_lines(stream_reader):asyncforlineinstream_reader:yieldjson.loads(line)
但这段代码也做了同样的事情,并且在Python3.5+上运行:
fromasync_generatorimportasync_generator,yield_@async_generatorasyncdefload_json_lines(stream_reader):asyncforlineinstream_reader:awaityield_(json.loads(line))
或者在Python3.7中,您可以编写:
fromcontextlibimportasynccontextmanager@asynccontextmanagerasyncdefbackground_server():asyncwithtrio.open_nursery()asnursery:value=awaitnursery.start(my_server)try:yieldvaluefinally:# Kill the server when the scope exitsnursery.cancel_scope.cancel()
这是相同的,但回到3.5:
fromasync_generatorimportasync_generator,yield_,asynccontextmanager@asynccontextmanager@async_generatorasyncdefbackground_server():asyncwithtrio.open_nursery()asnursery:value=awaitnursery.start(my_server)try:awaityield_(value)finally:# Kill the server when the scope exitsnursery.cancel_scope.cancel()
(如果您使用的是3.6,那么可以使用@asynccontextmanager和 本机生成器。)
让我们这样做
- 安装:python3 -m pip install -U async_generator(或在Windows上, 也许py -3-m pip install -U async_generator
- 手册:https://async-generator.readthedocs.io/
- bug跟踪器和源代码:https://github.com/python-trio/async_generator
- 实时聊天:https://gitter.im/python-trio/general
- 许可证:MIT或Apache2,由您选择
- 投稿指南:https://trio.readthedocs.io/en/latest/contributing.html
- 行为准则:请贡献者遵循我们的code of conductin 所有项目空间。
为什么有些链接会提到“三人组”?
Trio是一种新的异步并发 专注于可用性和正确性的python库 想让easy获得东西right。那async_generator 图书馆是由三重奏计划维护的,也是这个任务的一部分。 因为trio在内部使用async_generator。
您可以对任何异步库使用async_generator。效果很好 用asyncio,或者twisted,或者你喜欢的任何东西。(但我们认为三人组 很可爱。)