2016-03-31 36 views
0

我試圖檢測擊鍵在Python 3.X在Mac碼頭,這裏是我的代碼有Python 3.x密鑰檢測。 print語句來鍵後,檢測功能

import tty 
import termios 
import sys 


def get_key(): 
    fd = sys.stdin.fileno() 
    old_settings = termios.tcgetattr(fd) 
    try: 
     tty.setraw(sys.stdin.fileno()) 
     ch = sys.stdin.read(1) 
    finally: 
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 
    return ch 


def key_detect(): 
    print("Key detect: ", end="") 
    print(get_key()) 


while True: 
    key_detect() 

我想它的工作原理是:

Key detect: 

並等到我按下某個東西,打印結果,並且應該等待下一次。就像這樣:

Key detect: a 
Key detect: 

但它是這樣的:

// A cursor flashes, but nothing has been printed 

而當我追問了一句:

Key detect: a 
*cursor* 

回答

2

沒有被寫到標準輸出(這是印刷())做在它被刷新之前。這種情況在print()以標準換行符結束時隱式發生,但是當您提供不同的end =「」像這樣(並且字符串很短)時,隱式刷新不會發生。

您可以刷新標準輸出明確,並能解決問題:

def key_detect(): 
    print("Key detect: ", end="") 
    sys.stdout.flush() 
    print(get_key()) 
+1

或者關於Python 3.3及以上,則可以提供'沖水= TRUE'到'print'功能。 – user2357112

+0

非常感謝它:) – terryy