我试图在Mac终端中检测Python 3.x中的按键,这里是我的代码
import tty
import termios
import sys
def get_key():
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
def key_detect():
print("Key detect: ", end="")
print(get_key())
while True:
key_detect()
我认为它的作用如下:
Key detect:
等到我按某事,打印结果,然后等待下次。像这样:
Key detect: a
Key detect:
但它是这样的:
// A cursor flashes, but nothing has been printed
当我按下某事时:
Key detect: a
*cursor*
答案 0 :(得分:2)
在刷新之前,没有任何内容写入stdout(print())。当print()以标准换行结束时隐式发生这种情况,但是当你提供不同的end =“”(并且字符串很短)时,隐式刷新不会发生。
您可以显式刷新stdout,并解决问题:
def key_detect():
print("Key detect: ", end="")
sys.stdout.flush()
print(get_key())