2010-08-19 42 views
14

我在Python中使用raw_input與shell中的用戶交互。python中的raw_input沒有按下輸入

c = raw_input('Press s or n to continue:') 
if c.upper() == 'S': 
    print 'YES' 

它按預期工作,但用戶必須在按's'後按下enter鍵。有沒有辦法從用戶輸入中完成我需要的內容,而無需在shell中按下輸入?我正在使用* nixes機器。

+0

[http://stackoverflow.com/questions/292095/polling-the-keyboard-in-python](http://stackoverflow .com/questions/292095/polling-the-keyboard-in-python) – 2010-08-19 15:21:29

+0

見此頁。它使用ttyl模塊,只有兩行。只是省略了ord()命令:http://stackoverflow.com/questions/575650/how-to-obtain-the-keycodes-in-python – incognick 2012-08-02 22:47:47

回答

11

在Windows下,你需要的msvcrt模塊,具體而言,它似乎從你描述你的問題的方式,功能msvcrt.getch

閱讀按鍵和返回 產生的字符。沒有什麼是 呼應到控制檯。如果按鍵不是已經有 可用,則此通話將阻止 ,但不會等待輸入 被按下。

(等 - 請參閱我剛纔指出的文檔)。對於Unix,請參閱this recipe爲一個簡單的方法來建立一個類似的getch函數(在該配方的註釋線程中也可以看到幾個替代品& c)。

+0

它按預期工作,並且擁有跨平臺的解決方案非常棒。謝謝回答! – 2010-08-19 16:24:11

+0

@有人,不客氣! – 2010-08-19 17:50:02

+0

直接訪問https://pypi.python.org/pypi/readchar,似乎可以完成大部分操作,但我無法正確讀取OSX上的箭頭鍵。 – boxed 2015-04-06 18:59:00

8

Python不提供多平臺解決方案。
如果您使用的是Windows,你可以嘗試用msvcrt

import msvcrt 
print 'Press s or n to continue:\n' 
input_char = msvcrt.getch() 
if input_char.upper() == 'S': 
    print 'YES' 
+0

我遇到過這個模塊,但我需要它在* nixes上工作。不管怎麼說,還是要謝謝你! – 2010-08-19 16:15:37

3

取而代之的是msvcrt模塊,您還可以使用WConio

>>> import WConio 
>>> ans = WConio.getkey() 
>>> ans 
'y' 
1

在一個側面說明,msvcrt.kbhit()返回布爾值確定當前是否按下鍵盤上的任何鍵。

因此,如果您正在製作遊戲或其他東西,並希望按鍵操作而不是完全停止遊戲,則可以在if語句中使用kbhit()以確保僅在用戶實際想要做點什麼。

在Python 3的一個例子:

# this would be in some kind of check_input function 
if msvcrt.kbhit(): 
    key = msvcrt.getch().decode("utf-8").lower() # getch() returns bytes data that we need to decode in order to read properly. i also forced lowercase which is optional but recommended 
    if key == "w": # here 'w' is used as an example 
     # do stuff 
    elif key == "a": 
     # do other stuff 
    elif key == "j": 
     # you get the point 
1

要得到一個字符,我用getch,但我不知道這是否適用於Windows。

2

詛咒可以做到這一點還有:

import curses, time 

#-------------------------------------- 
def input_char(message): 
    try: 
     win = curses.initscr() 
     win.addstr(0, 0, message) 
     while True: 
      ch = win.getch() 
      if ch in range(32, 127): break 
      time.sleep(0.05) 
    except: raise 
    finally: 
     curses.endwin() 
    return chr(ch) 
#-------------------------------------- 
c = input_char('Press s or n to continue:') 
if c.upper() == 'S': 
    print 'YES'