python - 有没有 python 异步文件处理程序?
问题描述
我目前依赖于asyncio.to_thread
运行阻塞代码,例如文件处理。
有没有更好的方法来做到这一点?
PSaiofile
似乎也没有好转。
乐
提供我目前正在测试的内容:
import asyncio
import uvloop
import time
from pathlib import Path
async def aio(i):
path = Path(f'io_test/async/{i}')
await asyncio.to_thread(path.mkdir, parents=True, exist_ok=True)
with await asyncio.to_thread(open, f'{path}/f.py', 'w') as f:
await asyncio.to_thread(f.write, "print('Hello World!')")
def io(i):
path = Path(f'io_test/blocking/{i}')
path.mkdir(parents=True, exist_ok=True)
with open(f'{path}/f.py', 'w') as f:
f.write("print('Hello World!')")
async def async_main(n):
ts = time.time()
coroutines = [aio(i) for i in range(n)]
await asyncio.gather(
*coroutines
)
te = time.time()
delta = te - ts
print(f'ASYNC IO | Took {delta} seconds.')
def main(n):
ts = time.time()
[io(i) for i in range(n)]
te = time.time()
delta = te - ts
print(f'BLOCKING IO | Took {delta} seconds.')
if __name__ == '__main__':
uvloop.install()
loop = asyncio.get_event_loop()
tasks = 1000
# async test
asyncio.run(async_main(tasks))
# blocking test
main(tasks)
预期与否,“阻塞”过程相当快(2 倍甚至 3 倍)。我不能不使用 async 的原因是我真的无法承受流程中的阻塞点。
解决方案
推荐阅读
- html - 我应该有一个表格还是两个单独的表格
- windows - 权限被拒绝:Untitled.ipynb Windows 10 AWS 工作区
- javascript - Google Apps 脚本 - 按标签颜色获取工作表
- javascript - 如何在 Angular JS 中将 Service 中的值暴露给 HTML
- scala - 为什么 scala @tailrec 不能在 Option.flatMap 上使用?
- reactjs - setState 具有先前返回的自定义挂钩的值
- python - python 64位,多处理未使用最大值
- android - Kotlin Android 中的日志和单元测试
- python-3.x - KMeans 聚类 - 值错误:n_samples=1 应该 >= n_cluster
- vue.js - NativeScript 所有调试版本都正常工作,发布版本崩溃