Cyker Cyker - 2 months ago 22
Python Question

What's Python's equivalent to C's read function?



The read() function shall attempt to read nbyte bytes from the file associated with the open file descriptor, fildes, into the buffer pointed to by buf.

Upon successful completion, these functions shall return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions shall return −1 and set errno to indicate the error.


Read at most n characters from stream.

Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.

Bold fonts are mine. Basically Python will insist on finding EOF if currrently available data is less than buffer size... How to make it simply return whatever is available?


By "Python's read" I assume you mean the read method of file objects. That method is closer in spirit to C's fread: it implements buffering and it tries to satisfy the requested amount, unless that is impossible due to an IO error or end-of-file condition.

If you really need the behavior of C's read(), you can call to invoke the underlying C function. The only difference is that it returns the data read as a byte string, and it raises an exception in the cases when the C function would return -1.

If you call, remember to give it the file descriptor obtained using the fileno method on file objects, or returned by functions in the os module such as, os.pipe, etc. Also remember not to mix calls to and, since the latter does buffering and can cause later calls to not to return the buffered data.