我试图在python中读取一个字符,以便根据输入执行操作。我知道在谷歌的帮助下,没有简单的方法可以在python中读取击键。我终于找到了' readchar' 这个包很有希望,但是我无法让它在一个简单的程序中运行。非常感谢任何帮助。
import readchar
def keyprint():
while True:
print "Press 'A' to Start the recording"
print " 'Z' to Stop the recording"
print " 'Enter' to quit the program..."
# Read a key
key = readchar.readkey()
if(key == 'A'):
print "Started Recording..."
elif(key == 'Z'):
print "Stopped Recording..."
elif(key == '\r'):
print "Exiting..."
break
else:
print "Please Use only allowed keys: A, Z, Enter!"
if __name__ == "__main__":
keyprint()
编辑:输出错误
File "/home/inblueswithu/Documents/LM_DataCollection/keystroke_test.py", line 22, in <module>
keyprint()
File "/home/inblueswithu/Documents/LM_DataCollection/keystroke_test.py", line 10, in keyprint
key = readchar.readkey()
File "/home/inblueswithu/.local/lib/python2.7/site-packages/readchar/readchar.py", line 20, in readkey
c1 = getchar()
File "/home/inblueswithu/.local/lib/python2.7/site-packages/readchar/readchar_linux.py", line 12, in readchar
old_settings = termios.tcgetattr(fd)
termios.error: (25, 'Inappropriate ioctl for device')
谢谢, inblueswithu
答案 0 :(得分:2)
在github上与项目的创建者 - magmax(here)讨论了这个问题之后,我理解readchar
包只有在你尝试从终端运行而不是从任何IDE运行时才有效或其他非终端执行。导致该错误的原因是它尝试获取在这种情况下不存在的终端设置。
我一直试图从Wing IDE运行它。如果您尝试从终端运行它,程序将运行良好。
P.S:magmax建议使用readchar.keys.ENTER
代替\r
。并建议查看https://github.com/magmax/python-inquirer&amp; its examples