蟒蛇在Linux中:将用户输入到异步队列(Python in Linux: Put user inp

2019-10-29 01:27发布

我试图运行一个程序,它在输入的作业得到完成。 我已经通过几种形式看,神情到文档 。 我在Debian中运行这个,我明白,我可以用这个残培功能没有击中返回键接收字符。 要打破它,这就是我想在我的无限while循环来实现

  • 以在输入(线程没有在这里工作,我
  • 将输入到队列
  • 如果没有运行的作业,开始与项中的任务队列的前面作为变量

我也运行线程模块来执行其它指令。 有没有什么办法可以做到这一点?


更新:这是我到目前为止已经试过:

首先,我试图用一个定时器从线程模块从等待,其中又以这样的事情停下来。

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

这里的问题是,它仍然在等待用户输入。

然后我试图把残培功能到另一个线程。

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

这种尝试不会让我做任何事情。

Answer 1:

我阅读这个的链接 ,并且有什么,我在底部希望的实现。

我使用的选择模块在Linux非阻塞的实现。 这时候出(这里5秒),如果没有收到输入。 在一个线程中使用时,使残培通话无阻塞将允许线程完全退出特别有用

# This class gets a single character input from the keyboard
class _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


Answer 2:

我也用[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()


文章来源: Python in Linux: Put user input asynchronously into queue