注:我想这样做,无需使用任何外部包装,像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 –