2013-03-08 55 views
0

我試圖運行一個程序,它在輸入完成後接受輸入。我已經瀏覽了幾種表格,並查看了documentation。我在Debian上運行這個程序,並且我明白我可以使用這個getch function來接收字符而不用按回車鍵。要打破它,這就是我想在我的無限實現while循環Linux中的Python:將用戶輸入異步放入隊列

  • 採取輸入(線程沒有在這裏工作,我
  • 來把輸入到隊列
  • 如果沒有正在運行的作業,開始與項中的任務隊列的前面作爲變量

我也運行線程模塊來執行其它指令。請問有什麼辦法可以做到這一點?


更新:這是我到目前爲止已經試過:

首先,我試圖用一個定時器從線程模塊從等待,其中又以這樣的事情停下來。

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 

這種嘗試不讓我做任何事情。

+0

是的,但也許如果你提供的,你已經嘗試過什麼想法,我們可以幫助你到達那裏。 – Michael 2013-03-08 20:49:59

+0

@Michael剛剛更新 – user2125538 2013-03-08 21:03:44

+0

撇開這個問題,你爲什麼試圖從終端運行這樣的事情,我建議你使用'curses'來滿足你所有的高級終端輸入和輸出需求。 – 9000 2013-03-08 21:57:00

回答

0

我讀了更多這link,並有一個實現我想要的底部。

我在Linux上對非阻塞實現使用了select模塊。 如果沒有收到任何輸入,則超時(此處爲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 
+1

領先的空格是句法。此代碼不起作用。 – gecko 2013-03-10 21:38:58

0

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