2014-09-25 44 views
1

我一直在試圖編寫鍵盤監聽器而不安裝任何軟件包。我想要的是創建一個無阻塞的方式來只讀取用戶輸入的一個字符。所以我創建了另一個線程,除了主線程之外。這裏是我的代碼:在python中使用多線程打印函數的意外縮進輸出

import sys, os 
import thread 
import time 

try: 
    from msvcrt import getch 
except ImportError: 
    def getch(): 
     import sys, tty, termios 
     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 

char = None; 

def key_listener(): 
    global char; 
    while True: 
     char = getch() 
     # escape key to exit 
     if ord(char) == 27: 
      break 
     #print char  #comment this line for test 

thread.start_new_thread(key_listener,()) 

while True: 
    print("Whatever") 
    time.sleep(1); 

和印刷字符串有點不可思議:

Yinans-MacBook-Pro:anaconda game Yinan$ python inputtest.py 
Whatever 
    Whatever 
      Whatever 
        Whatever 
          Whatever 
            Whatever 

看到那些縮進?我從來沒有想到會有這個。我一整個下午都在試着解決它,但都失敗了。有人知道如何解決這個問題嗎?我會很感激。 (順便說一句,我使用的是一個macbook專業版。)

回答

2

將STDIN置於原始模式,將STDOUT也置於原始模式,所以正常的\n未擴展爲CRLF。您需要在字符串的末尾打印\r,以便將光標返回到第一列。

+0

這很有道理,但我無法在Python模塊文檔中找到任何有關此內容的信息。你有這個簡單的參考? – EOL 2014-09-25 02:35:00

+0

http://en.wikipedia.org/wiki/POSIX_terminal_interface#History – 2014-09-25 02:37:10

+0

我想「無行編輯」是指https://en.wikipedia.org/wiki/POSIX_terminal_interface#Output_processing中描述的換行符行爲?我不熟悉終端文檔的技術語言...... :) – EOL 2014-09-25 09:39:36