注:我想這樣做,無需使用任何外部包裝,像pygame的,等實時抓拍和按鍵的處理(例如按鍵事件)
我試圖捕捉單個按鍵爲他們到達並針對特定角色執行操作,無論我是僅僅想「重新回顯」角色,還是根本不顯示它並執行其他操作。
我已經找到了一個跨平臺(雖然關於OS X不知道)的getch()實現,因爲我不想念想輸入一整行()的作用:
# http://code.activestate.com/recipes/134892/
def getch():
try:
import termios
except ImportError:
# Non-POSIX. Return msvcrt's (Windows') getch.
import msvcrt
return msvcrt.getch
# POSIX system. Create and return a getch that manipulates the tty.
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
[嘗試1 ] 我第一次嘗試了一個簡單的while-true循環來輪詢getch,但是如果我輸入得太快,字符就會丟失。減少睡眠時間會使情況變得更糟。調試語句只在輸入鍵的按下時打印,並且在時間和位置上不一致。 (看起來可能有一些線路緩衝正在進行?)取出環路和睡眠可以讓它工作一次,但完美。
#!/usr/bin/env python3
import sys
import tty
import time
def main():
while True:
time.sleep(1)
sys.stdout.write(" DEBUG:Before ")
sys.stdout.write(getch())
sys.stdout.write(" DEBUG:After ")
if __name__ == "__main__":
main()
[嘗試2] 我得到一個例子使用螺紋的方法(https://stackoverflow.com/a/14043979/2752206),但它「鎖死」,將不接受任何輸入(包括Ctrl-C
,和等等)..
#!/usr/bin/env python3
import sys
import tty
import time
import threading
key = 'Z'
def main():
threading.Thread(target=getchThread).start()
while True:
time.sleep(1)
sys.stdout.write(" DEBUG:Before ")
sys.stdout.write(key)
sys.stdout.write(" DEBUG:After ")
def getchThread():
global key
lock = threading.Lock()
while True:
with lock:
key = getch()
if __name__ == "__main__":
main()
有沒有人有任何建議或指導?或者更重要的是,有人可以解釋爲什麼這兩次嘗試不起作用?謝謝。
您返回函數'msvcrt.getch',但不是被調用的結果。 – zondo
謝謝你的收穫。我修改了一段代碼,但是我在Linux上。 = P –