Python 终端变得无反应
运行此脚本后:Python 终端变得无反应,python,terminal,Python,Terminal,运行此脚本后: def getVal(): import sys,tty tty.setcbreak(sys.stdin) key = ord(sys.stdin.read(1)) while not (key == 97 or key == 100 or key == 115 or key == 100): print("Please enter w, a, s, or d only.") key = ord(sys.stdi
def getVal():
import sys,tty
tty.setcbreak(sys.stdin)
key = ord(sys.stdin.read(1))
while not (key == 97 or key == 100 or key == 115 or key == 100):
print("Please enter w, a, s, or d only.")
key = ord(sys.stdin.read(1))
if key == 119:
print("Up")
elif key == 97:
print("Left")
elif key == 115:
print("Down")
elif key == 100:
print("Right")
getVal()
我尝试在终端中再次运行它,但无论我尝试做什么,它都不会让我键入任何内容,并且命令c或命令z不起作用(我在mac上)。有没有办法解决这个问题?您的终端没有责任,因为您的代码禁用了字符回音,但忘记了重新启用它 我建议您存储终端属性,并在读取密钥后恢复它们:
import sys
import tty
import termios
def getVal():
old = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
try:
key = ord(sys.stdin.read(1))
while not (key == 97 or key == 100 or key == 115 or key == 119):
print("Please enter w, a, s, or d only.")
key = ord(sys.stdin.read(1))
if key == 119:
print("Up")
elif key == 97:
print("Left")
elif key == 115:
print("Down")
elif key == 100:
print("Right")
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old)
getVal()
尝试cmd-\n也可以退出,您应该在文件顶部执行导入操作,而不是在函数中。另外,当您可以比较
键==“w”
时,为什么要调用ord
?