Linux中的Python:将用户输入异步放入队列
我正在尝试运行一个程序,在工作完成时接收输入。我已经浏览了好几种表格,并研究了其中的原因。我在Debian中运行它,我知道我可以使用它来接收字符,而无需点击返回键。分解一下,这就是我试图在无限while循环中实现的Linux中的Python:将用户输入异步放入队列,python,linux,asynchronous,queue,user-input,Python,Linux,Asynchronous,Queue,User Input,我正在尝试运行一个程序,在工作完成时接收输入。我已经浏览了好几种表格,并研究了其中的原因。我在Debian中运行它,我知道我可以使用它来接收字符,而无需点击返回键。分解一下,这就是我试图在无限while循环中实现的 接收输入(线程在这里对我不起作用 将输入放入队列 如果没有正在运行的作业,则以队列前面的项目作为变量启动作业 我还运行线程模块来执行另一条指令。有什么方法可以做到这一点吗 更新:这是我迄今为止尝试过的: 首先,我尝试使用线程模块中的计时器来阻止它等待,就像这样 def getc
- 接收输入(线程在这里对我不起作用
- 将输入放入队列
- 如果没有正在运行的作业,则以队列前面的项目作为变量启动作业
更新:这是我迄今为止尝试过的: 首先,我尝试使用线程模块中的计时器来阻止它等待,就像这样
def getchnow():
def time_up():
answer= None
print 'time up...'
wait = Timer(5,time_up) # x is amount of time in seconds
wait.start()
try:
print "enter answer below"
answer = getch()
except Exception:
print 'pass\n'
answer = None
if answer != True: # it means if variable have somthing
wait.cancel() # time_up will not execute(so, no skip)
return answer
line = getchnow()
#Add line variable to queue
#Do stuff with queue
这里的问题是它仍然等待用户输入
然后,我尝试将getch函数放到另一个线程中
q = Queue.Queue
q.put(getch())
if q.get() != True: # it means if variable have somthing
line = q.get()
#Add line variable to queue
#Do stuff with queue
这一尝试没有让我做任何事情。我读了更多这方面的内容,在底部有一个我想要的实现
我使用select模块在Linux上实现非阻塞。
如果未收到任何输入,则此超时(此处为5秒)。
在线程中使用时特别有用,因此getch调用
无阻塞,允许线程干净地退出
我还使用了
[I,o,e]=select([sys.stdin.fileno()],[],[],[],[],2)
,但我听说它可能无法在windows上工作。如果任何人仍然需要多线程、非阻塞输入示例:
import threading
import sys
import time
bufferLock=threading.Lock()
inputBuffer=[]
class InputThread(threading.Thread):
def run(self):
global inputBuffer
print("starting input")
while True:
line=sys.stdin.readline()
bufferLock.acquire()
inputBuffer.insert(0,line)
bufferLock.release()
input_thread=InputThread()
input_thread.start()
while True:
time.sleep(4)
bufferLock.acquire()
if len(inputBuffer)>0:
print("Popping: "+inputBuffer.pop())
bufferLock.release()
是的,但是如果你提供一个你尝试过的想法,我们可能会帮助你达到目的。@Michael刚刚更新了一个问题,抛开你为什么要在终端上运行这样的东西不谈,我建议你使用
诅咒来满足所有高级终端的输入和输出需求。@9000你能告诉我一种用c来实现这一点的方法吗urses模块?您需要使用select()在不阻塞的情况下进行轮询,或者您可以使用termios。您可以在Linux上使用select()和stdin,但无法移植到Windows。
import threading
import sys
import time
bufferLock=threading.Lock()
inputBuffer=[]
class InputThread(threading.Thread):
def run(self):
global inputBuffer
print("starting input")
while True:
line=sys.stdin.readline()
bufferLock.acquire()
inputBuffer.insert(0,line)
bufferLock.release()
input_thread=InputThread()
input_thread.start()
while True:
time.sleep(4)
bufferLock.acquire()
if len(inputBuffer)>0:
print("Popping: "+inputBuffer.pop())
bufferLock.release()