从事一个使用小键盘和电子墨水显示器的项目,该显示器将在树莓派零上运行。我已经为 python (pynput、pyxhook) 尝试了几个键盘包,并编写/测试了在我的桌面 (ubuntu) 上运行良好的简单击键记录器
但是我尝试在没有监视器的情况下在 pi 上运行它们两个库都死了
DisplayConnectionError: Can't connect to display ":0": [Errno 111] Connection refused
我知道至少 pyxhook 有能力捕捉鼠标移动,所以它为什么会“需要”访问监视器是有道理的。但我想要的只是一种在后台运行但没有连接监视器的进程中捕获键盘输入的方法
库还可以返回当前具有焦点的窗口作为关键事件的一部分,这可能是监视器如此深入的另一个原因。我试过了
$export DISPLAY=":0"
没有帮助。
这是pynput的简单代码,可与监视器一起使用,但在无头运行时不可用(从SSH运行)
#!/usr/bin/env python
from pynput import keyboard
def on_press(key):
print('Key {} pressed.'.format(key))
if str(key) == 'Key.esc':
print('Exiting...')
return False
with keyboard.Listener(on_press = on_press) as listener:
listener.join()
有什么方法可以让这些工作,或者可能有不同的方法来解决这个问题。
上述程序的完整堆栈跟踪失败
Traceback (most recent call last):
File "./keylog.py", line 3, in <module>
from pynput import keyboard
File "/usr/local/lib/python2.7/dist-packages/pynput/__init__.py", line 23, in <module>
from . import keyboard
File "/usr/local/lib/python2.7/dist-packages/pynput/keyboard/__init__.py", line 49, in <module>
from ._xorg import KeyCode, Key, Controller, Listener
File "/usr/local/lib/python2.7/dist-packages/pynput/keyboard/_xorg.py", line 38, in <module>
from pynput._util.xorg import (
File "/usr/local/lib/python2.7/dist-packages/pynput/_util/xorg.py", line 38, in <module>
_check()
File "/usr/local/lib/python2.7/dist-packages/pynput/_util/xorg.py", line 36, in _check
display = Xlib.display.Display()
File "/usr/local/lib/python2.7/dist-packages/Xlib/display.py", line 89, in __init__
self.display = _BaseDisplay(display)
File "/usr/local/lib/python2.7/dist-packages/Xlib/display.py", line 71, in __init__
protocol_display.Display.__init__(self, *args, **keys)
File "/usr/local/lib/python2.7/dist-packages/Xlib/protocol/display.py", line 90, in __init__
self.socket = connect.get_socket(name, protocol, host, displayno)
File "/usr/local/lib/python2.7/dist-packages/Xlib/support/connect.py", line 87, in get_socket
return mod.get_socket(dname, protocol, host, dno)
File "/usr/local/lib/python2.7/dist-packages/Xlib/support/unix_connect.py", line 113, in get_socket
raise error.DisplayConnectionError(dname, str(val))
Xlib.error.DisplayConnectionError: Can't connect to display ":0": [Errno 111] Connection refused