Refactor read with timeout logic into its own function
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user