Python In Linux: Put User Input Asynchronously Into Queue
I am trying to run a program that takes in input as a job is getting done. I have looked through several forms, and looked into the documentation. I'm running this in Debian, and
Solution 1:
I read more of this link, and there was an implementation of what I wanted at the bottom.
I used the select module for a Non-Blocking implementation on Linux. This times out in (5 seconds here) if no input is received. Particularly useful when used in a thread, so that the getch call is non-blocking and will allow the thread to exit cleanly
# This class gets a single character input from the keyboardclass_GetchUnix:
def__init__(self):
import tty, sys
from select import select
def__call__(self):
import sys, tty, termios
from select import select
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
[i, o, e] = select([sys.stdin.fileno()], [], [], 2)
if i:
ch=sys.stdin.read(1)
else:
ch=''finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
getch = _GetchUnix()
# End Class
Solution 2:
I've also used [i, o, e] = select([sys.stdin.fileno()], [], [], 2)
, but I've heard it might not work on windows. If anyone still needs a multi-threaded, non-blocking input example:
import threading
import sys
import time
bufferLock=threading.Lock()
inputBuffer=[]
classInputThread(threading.Thread):
defrun(self):
global inputBuffer
print("starting input")
whileTrue:
line=sys.stdin.readline()
bufferLock.acquire()
inputBuffer.insert(0,line)
bufferLock.release()
input_thread=InputThread()
input_thread.start()
whileTrue:
time.sleep(4)
bufferLock.acquire()
iflen(inputBuffer)>0:
print("Popping: "+inputBuffer.pop())
bufferLock.release()
Post a Comment for "Python In Linux: Put User Input Asynchronously Into Queue"