Cyker Cyker - 2 days ago 6
Python Question

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

C's

read
:


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.


Python's
read
:


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?

Answer

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 os.read() 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 os.read(), 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.open, os.pipe, etc. Also remember not to mix calls to os.open() and file.open(), since the latter does buffering and can cause later calls to os.open() not to return the buffered data.

Comments