Skip to content

Instantly share code, notes, and snippets.

@conrad784
Created December 14, 2018 15:50
Show Gist options
  • Save conrad784/862b9d050e5018104d2e7ea900d057b8 to your computer and use it in GitHub Desktop.
Save conrad784/862b9d050e5018104d2e7ea900d057b8 to your computer and use it in GitHub Desktop.
nonblocking read function for python, e.g. for named pipes
def read_nonblocking(path, bufferSize=100, timeout=.100):
import time
"""
implementation of a non-blocking read
works with a named pipe or file
errno 11 occurs if pipe is still written too, wait until some data
is available
"""
grace = True
result = []
try:
pipe = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
while True:
try:
buf = os.read(pipe, bufferSize)
if not buf:
break
else:
content = buf.decode("utf-8")
line = content.split("\n")
result.extend(line)
except OSError as e:
if e.errno == 11 and grace:
# grace period, first write to pipe might take some time
# further reads after opening the file are then successful
time.sleep(timeout)
grace = False
else:
break
except OSError as e:
if e.errno == errno.ENOENT:
pipe = None
else:
raise e
return result
@erm3nda
Copy link

erm3nda commented Apr 15, 2021

Pretty good, this is the key os.O_NONBLOCK.
Thank you.

If edit the return result to return [x for x in result if x] to avoid return empty items in the list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment