简体   繁体   English

python文件般的缓冲对象

[英]python file-like buffer object

I've written a buffer class that provides a File-like interface with read , write , seek , tell , flush methods to a simple string in memory. 我编写了一个缓冲类,它为内存中的一个简单字符串提供了一个类似文件的接口,其中包含readwriteseektellflush方法。 Of course it is incomplete (eg I didn't write readline ). 当然它是不完整的(例如我没有写readline )。 It's purpose is to be filled by a background thread from some external data source, but let a user treat it like a file. 它的目的是由来自某些外部数据源的后台线程填充,但让用户将其视为文件。 I'd expect it to contain a relatively small amount of data (maybe 50K max) 我希望它包含相对少量的数据(最多50K)

Is there a better way to do this instead of writing it from scratch? 有没有更好的方法来做到这一点,而不是从头开始编写?

You can use the standard Python modules StringIO or cStringIO to obtain an in-memory buffer which implements the file interface . 您可以使用标准Python模块StringIOcStringIO来获取实现文件接口的内存缓冲区。

cStringIO is implemented in C, and will be faster, so you should use that version if possible. cStringIO在C中实现,并且速度更快,因此如果可能,您应该使用该版本。

If you're using Python 3 you should use the io.StringIO instead of StringIO and io.BytesIO instead of cStringIO . 如果您使用的是Python 3,则应使用io.StringIO而不是StringIOio.BytesIO而不是cStringIO

我想你可能正在寻找StringIO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM