Created
December 14, 2018 15:50
-
-
Save conrad784/862b9d050e5018104d2e7ea900d057b8 to your computer and use it in GitHub Desktop.
nonblocking read function for python, e.g. for named pipes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty good, this is the key
os.O_NONBLOCK
.Thank you.
If edit the
return result
toreturn [x for x in result if x]
to avoid return empty items in the list.