在 async-await 函数中打开文件 python
我正在使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
aiofiles.open
返回的东西不是一个常规的类似文件的对象,需要等待它的操作:话又说回来,这并没有多大帮助,因为反序列化仍然会发生在阻塞方式(只有读取文件才是异步的)。
一般注意事项:即使某些接口需要异步函数,其内部发生的情况也没有限制。您只需在正常的阻塞函数前面编写
async
,它就会正常工作(当然没有async
/await
的好处)。The thing returned by
aiofiles.open
is not a regular file-like object, its operations need to be awaited: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 ofasync
/await
of course).