在python中从键盘读取原始输入 [英] read raw input from keyboard in python
问题描述
我正在尝试使用python获取键盘的原始输入.我有一个带可编程键的Logitech游戏键盘,但是Logitech不提供Linux驱动程序.所以我认为我可以(尝试)为此编写自己的驱动程序.考虑到解决方案可能是这样的:
I'm trying to get the raw input of my keyboard in python. I have a Logitech gaming keyboard with programmable keys, but Logitech doesn't provide drivers for Linux. So i thought i could (try) to write my own driver for this. In think the solution could be something like:
with open('/dev/keyboard', 'rb') as keyboard:
while True:
inp = keyboard.read()
-do something-
英语不是我的母语.如果发现错误,请更正.
English isn't my native language. If you find errors, please correct it.
推荐答案
import sys
for line in sys.stdin.readlines():
print line
这是针对您的问题的一种简单"解决方案,考虑到它读取sys.stdin,则可能需要驱动程序,并且如果OS沿途剥离内容,则可能会损坏.
This is one "simple" solution to your problem considering it reads sys.stdin you'll probably need a driver and if the OS strips stuff along the way it will probably break anyways.
这是另一种解决方案(仅Linux afaik):
This is another solution (linux only afaik):
import sys, select, tty, termios
class NonBlockingConsole(object):
def __enter__(self):
self.old_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
return self
def __exit__(self, type, value, traceback):
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
def get_data(self):
try:
if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
return sys.stdin.read(1)
except:
return '[CTRL-C]'
return False
data = ''
printed = ''
last = ''
with NonBlockingConsole() as nbc:
while 1:
c = nbc.get_data()
if c:
if c == '\x1b': # x1b is ESC
break
elif c == '\x7f': # backspace
data = data[:-1]
printed = data[:-1]
last = ''
sys.stdout.write('\b')
elif c == '[CTRL-C]':
data = ''
last = ''
sys.stdout.write('\n')
elif c == '\n': # it's RETURN
sys.stdout.write('\n')
# parse data here
data = ''
else:
data += (c)
last = c
sys.stdout.write(c)
驱动程序有问题吗?
如果以上方法均无效,则无法在Python中获取键.
很可能您将需要一个实际的驱动程序来解析从键盘发送的数据,这不是USB堆栈上的正常键盘事件,这意味着.这对于Python来说是低级的,您很不走运. ..除非您知道如何构建linux驱动程序.
Driver issue?
If none of the above work, you woun't be able to get the keys within Python.
Most likely you'll need an actual driver that can parse the data sent from the keyboard that is not a normal keyboard event on the USB stack, meaning.. This is way to low-level for Python and you're out of luck... unless you know how to build linux drivers.
无论如何,请看: http://ubuntuforums.org/showthread.php? t = 1490385
好像有更多的人试图对此做些事情.
Looks like more people have tried to do something about it.
http://pyusb.sourceforge.net/docs/1.0/tutorial.html
您可以尝试PyUSB解决方案并从USB插槽中获取原始数据,但是再次..如果G键未注册为传统" USB数据,则它可能会丢失并且您将无法接收.
You could try a PyUSB solution and fetch raw data from the USB socket, but again.. if the G-keys are not registered as "traditional" USB data it might get dropped and you won't recieve it.
另一种未经测试的方法,但可能起作用//Hackaday:
Another untested method, but might work //Hackaday:
这篇关于在python中从键盘读取原始输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!