Refactor read with timeout logic into its own function

This commit is contained in:
Kovid Goyal
2018-01-08 12:48:14 +05:30
parent f3cb68ee40
commit 1f976644bf
2 changed files with 31 additions and 22 deletions
+26
View File
@@ -12,6 +12,7 @@ import shlex
import socket
import string
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from functools import lru_cache
@@ -264,3 +265,28 @@ def single_instance(group_id=None):
s.set_inheritable(False)
atexit.register(remove_socket_file, s)
return True
def read_with_timeout(more_needed, timeout=10, src=sys.stdin):
import termios
import tty
import fcntl
import select
fd = src.fileno()
old = termios.tcgetattr(fd)
oldfl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldfl | os.O_NONBLOCK)
tty.setraw(fd)
start_time = monotonic()
try:
while timeout > monotonic() - start_time:
rd = select.select([fd], [], [], max(0, timeout - (monotonic() - start_time)))[0]
if rd:
data = sys.stdin.buffer.read()
if not data:
break # eof
if not more_needed(data):
break
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
fcntl.fcntl(fd, fcntl.F_SETFL, oldfl)