我正在尝试让一个 Python 程序监听发送到作为子例程 (Popen) 启动的程序的击键。
问题在于,当聚焦到正确的窗口时,什么也不会发生。不确认已按下某个键。如果我从窗口点击到其他东西,它就会起作用。
此监听旨在调试无法将击键发送到程序(pyautogui、pynput、键盘,甚至 Popen)的问题。沟通不起作用。即使我自己在键盘上手动输入,Python 脚本也会忽略发送的击键。
我正在通过 Lutris 运行 Retroarch。我的电脑操作系统是Ubuntu Linux 22.04,显示管理器是Wayland。下面是代码:
from pynput import keyboard
import subprocess, time
def on_press(key):
print(key)
return False # stop listener; remove this if want more keys
lutris = f'LUTRIS_SKIP_INIT=1 lutris/bin/lutris lutris:rungameid/3'
p = subprocess.Popen(lutris, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
time.sleep(5)
listener = keyboard.Listener(on_press=on_press)
listener.start() # start to listen on a separate thread
listener.join() # remove if main thread is polling self.keys
我希望引用的代码块等待击键,并在收到击键后退出。
如果我将 Retroarch/Lutris 窗口聚焦(活动),则所有击键都会被忽略。
你是在 Wayland 还是 x 上运行? 我可以以某种方式重现这个问题,在 wayland 上,当鼠标悬停在雷鸟上时,我会收到鼠标事件,但不会收到火狐上的事件。
您可以通过在启动 lutris 之前将 $DISPLAY 设置为正确的环境变量来修复它吗?
On Linux, pynput uses X or uinput.
When running under X, the following must be true:
An X server must be running.
The environment variable $DISPLAY must be set.
When running under uinput, the following must be true:
You must run your script as root, to that is has the required permissions for uinput.
The latter requirement for X means that running pynput over SSH generally will not work. To work around that, make sure to set $DISPLAY:
$ DISPLAY=:0 python -c 'import pynput'
Please note that the value DISPLAY=:0 is just an example. To find the actual value, please launch a terminal application from your desktop environment and issue the command echo $DISPLAY.
When running under Wayland, the X server emulator Xwayland will usually run, providing limited functionality. Notably, you will only receive input events from applications running under this emulator.