我正在尝试使用 pynput('pijnput' 转换为痛苦的坑:-))模块来捕获键盘。这是我的代码:
class KeyPress:
def __init__(self,parent):
self.parent=parent
def on_press(self,key):
#keyboard.Listener.stop()
try:
self.parent.pressedKey=key.char
self.parent.pressedKeyCode=None
except AttributeError:
self.parent.pressedKey=key
self.parent.pressedKeyCode=key.value.vk
return False
def on_release(self,key):
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
def run(self):
with keyboard.Listener(
on_press=self.on_press,
on_release=self.on_release,suppress=True) as listener:
listener.join()
我创建了一个子类,它将键和 keyCode 分配给主类的属性如果我运行它,它可以正常工作,直到我按下一定数量的键然后 X 崩溃并出现此错误。起初我在 ipython + tmux 中运行它,但也在纯 bash 中运行,这种情况发生了。
Exception in thread Thread-131:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/site-packages/pynput/_util/__init__.py", line 136, in run
self._run()
File "/usr/lib/python3.7/site-packages/pynput/keyboard/_xorg.py", line 499, in _run
super(Listener, self)._run()
File "/usr/lib/python3.7/site-packages/pynput/_util/xorg.py", line 370, in _run
self._display_record = Xlib.display.Display()
File "/usr/lib/python3.7/site-packages/Xlib/display.py", line 89, in __init__
self.display = _BaseDisplay(display)
File "/usr/lib/python3.7/site-packages/Xlib/display.py", line 71, in __init__
protocol_display.Display.__init__(self, *args, **keys)
File "/usr/lib/python3.7/site-packages/Xlib/protocol/display.py", line 163, in __init__
auth_prot_data = auth_data)
File "/usr/lib/python3.7/site-packages/Xlib/protocol/display.py", line 1070, in __init__
display.send_and_recv(request = -1)
File "/usr/lib/python3.7/site-packages/Xlib/protocol/display.py", line 610, in send_and_recv
raise self.socket_error
Xlib.error.ConnectionClosedError: Display connection closed by server
我的猜测是我创建了太多线程,因为我没有终止它们。虽然我假设'with'构造会处理这个问题?这个对吗 ?如果是这样,我应该怎么做才能让它发挥作用?
提前致谢