Python中的主要侦听器? [英] Key Listeners in python?
问题描述
有没有一种方法可以在python中执行键监听程序而无需庞大的模块,例如pygame
?
Is there a way to do key listeners in python without a huge bloated module such as pygame
?
一个例子是,当我按下 a 键时,它将打印到控制台
An example would be, when I pressed the a key it would print to the console
按下了一个键!
The a key was pressed!
它还应该侦听箭头键/空格键/Shift键.
It should also listen for the arrow keys/spacebar/shift key.
推荐答案
不幸的是,做到这一点并不容易.如果您要制作某种文本用户界面,则可能需要查看 curses
.如果您想要像通常在终端中那样显示内容,但又想要这样的输入,则必须使用 termios
,不幸的是,在Python中该文献的文献很少.不幸的是,这些选项都不是那么简单.此外,它们在Windows下不起作用.如果您需要它们在Windows下运行,则必须使用 PDCurses 代替curses
或 pywin32 而不是termios
.
It's unfortunately not so easy to do that. If you're trying to make some sort of text user interface, you may want to look into curses
. If you want to display things like you normally would in a terminal, but want input like that, then you'll have to work with termios
, which unfortunately appears to be poorly documented in Python. Neither of these options are that simple, though, unfortunately. Additionally, they do not work under Windows; if you need them to work under Windows, you'll have to use PDCurses as a replacement for curses
or pywin32 rather than termios
.
我能够做到这一点.它打印出您键入的键的十六进制表示形式.正如我在对您的问题的评论中所说的那样,箭是很棘手的.我想你会同意的.
I was able to get this working decently. It prints out the hexadecimal representation of keys you type. As I said in the comments of your question, arrows are tricky; I think you'll agree.
#!/usr/bin/env python
import sys
import termios
import contextlib
@contextlib.contextmanager
def raw_mode(file):
old_attrs = termios.tcgetattr(file.fileno())
new_attrs = old_attrs[:]
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
try:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
yield
finally:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)
def main():
print 'exit with ^C or ^D'
with raw_mode(sys.stdin):
try:
while True:
ch = sys.stdin.read(1)
if not ch or ch == chr(4):
break
print '%02x' % ord(ch),
except (KeyboardInterrupt, EOFError):
pass
if __name__ == '__main__':
main()
这篇关于Python中的主要侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!