在 async-await 函数中打开文件 python

发布于 2025-01-11 20:04:54 字数 551 浏览 1 评论 0原文

我正在使用discord.py,它需要使用异步等待函数。 我想使用 pickle 和 JSON 模块转储和加载数据。 但是当尝试我收到此错误时,

AttributeError: __enter__
d:\Users\-------\visual studio projects\------------\main.py:65: RuntimeWarning: 
coroutine 'Command.__call__' was never awaited

我相信发生这种情况是因为正在打开内部文件和 async-await 函数。 所以我尝试了另一种方法来使用 aiofiles 打开具有异步函数的文件:

async with aiofiles.open("owners.pkl", mode="rb") as file:
    owner_dict = pickle.load(file)

但问题是 pickle 和 json 确实在异步函数内工作。

是否有其他方法可以在异步等待函数中使用 JSON 或 pickle 打开、加载和转储???

Am using discord.py which requires using async-await functions.
I want to dump and load data using pickle and JSON modules.
but when trying that I get this error

AttributeError: __enter__
d:\Users\-------\visual studio projects\------------\main.py:65: RuntimeWarning: 
coroutine 'Command.__call__' was never awaited

I believe this happened because am opening the file inside and async-await function.
so I tried an alternative way to open the files with async functions with aiofiles:

async with aiofiles.open("owners.pkl", mode="rb") as file:
    owner_dict = pickle.load(file)

but the problem is that pickle and json does work inside async functions.

Is there any alternative way to open, load, and dump with JSON or pickle inside async-await functions ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七堇年 2025-01-18 20:04:54

aiofiles.open 返回的东西不是一个常规的类似文件的对象,需要等待它的操作:

async with aiofiles.open("owners.pkl", mode="rb") as file:
    owner_dict = pickle.loads(await file.read())

话又说回来,这并没有多大帮助,因为反序列化仍然会发生在阻塞方式(只有读取文件才是异步的)。


一般注意事项:即使某些接口需要异步函数,其内部发生的情况也没有限制。您只需在正常的阻塞函数前面编写async,它就会正常工作(当然没有async/await的好处)。

The thing returned by aiofiles.open is not a regular file-like object, its operations need to be awaited:

async with aiofiles.open("owners.pkl", mode="rb") as file:
    owner_dict = pickle.loads(await file.read())

Then again, this doesn't really help all that much since the deserialization will still happen in a blocking way (only reading the file will be async).


And a general note: Even if some interface demands an async function, there's no restriction on what happens inside of it. You can just write async in front of a normal, blocking function, and it will just work (without the benefits of async/await of course).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文