Is there a way to make StringIO reading blocking
سؤال
I've searched through the documentation and searched around but there is nothing said about blocking StringIO objects.
I could create my own file-like object that just simply wraps around StringIO but how is the best way to make it blocking? The only way I know is to use a while loop and a time.sleep(0.1) till there is data available.
المحلول
import os
r, w = os.pipe()
r, w = os.fdopen(r, 'rb'), os.fdopen(w, 'wb')
Works exactly as I needed, this pipe function is sadly not very obvious in the documentation so I only found it later on.
نصائح أخرى
No, It's pretty obvious looking at the implementation of read()
def read(self, n = -1):
"""Read at most size bytes from the file
(less if the read hits EOF before obtaining size bytes).
If the size argument is negative or omitted, read all data until EOF
is reached. The bytes are returned as a string object. An empty
string is returned when EOF is encountered immediately.
"""
_complain_ifclosed(self.closed)
if self.buflist:
self.buf += ''.join(self.buflist)
self.buflist = []
if n is None or n < 0:
newpos = self.len
else:
newpos = min(self.pos+n, self.len)
r = self.buf[self.pos:newpos]
self.pos = newpos
return r
There is also this note at the top of the file
Notes:
- Using a real file is often faster (but less convenient).
So you may be better off using a real file anyway
لا تنتمي إلى StackOverflow