Read file with timeout in Python

Use

os.read(f.fileno(), 50)

instead. That does not wait until the specified amount of bytes has been read but returns when it has read anything (at most the specified amount of bytes).

This does not solve your issue in case you’ve got nothing to read from that pipe. In that case you should use select from the module select to test whether there is something to read.

EDIT:

Testing for empty input with select:

import select
r, w, e = select.select([ f ], [], [], 0)
if f in r:
  print os.read(f.fileno(), 50)
else:
  print "nothing available!"  # or just ignore that case

Leave a Comment