2009-06-27 28 views

回答

9

這是在Ubuntu 8.04.1,Python 2.5.2上工作,我沒有得到這樣的錯誤。也許你應該從命令行嘗試它,eclipse可能會使用它自己的標準輸入,如果我從Wing IDE運行它,我會得到完全相同的錯誤,但是從命令行它的效果很好。 原因是IDE如Wing使用自己的類netserver.CDbgInputStream作爲sys.stdin 所以sys.stdin.fileno爲零,那就是錯誤的原因。 基本上IDE標準輸入是不是tty(印刷sys.stdin.isatty()是假)

class _GetchUnix: 
    def __init__(self): 
     import tty, sys 

    def __call__(self): 
     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 


getch = _GetchUnix() 

print getch() 
+0

從命令行運行解決了問題。 – 2009-06-27 04:39:16

3

把端子插入原始模式並不總是一個好主意。實際上它足以清除ICANON位。這裏是另一個支持超時的getch()版本:

import tty, sys, termios 
import select 

def setup_term(fd, when=termios.TCSAFLUSH): 
    mode = termios.tcgetattr(fd) 
    mode[tty.LFLAG] = mode[tty.LFLAG] & ~(termios.ECHO | termios.ICANON) 
    termios.tcsetattr(fd, when, mode) 

def getch(timeout=None): 
    fd = sys.stdin.fileno() 
    old_settings = termios.tcgetattr(fd) 
    try: 
     setup_term(fd) 
     try: 
      rw, wl, xl = select.select([fd], [], [], timeout) 
     except select.error: 
      return 
     if rw: 
      return sys.stdin.read(1) 
    finally: 
     termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 

if __name__ == "__main__": 
    print getch() 
相關問題