从 udev 运行时 xrandr 失败

从 udev 运行时 xrandr 失败

以下摘录自 Python 3 脚本“myscript”,该脚本用于检测屏幕布局并使用 xrandr 刷新它,在使用sudo /usr/local/bin/myscript或运行时可以正常工作/usr/local/bin/myscript

xrandr_cmd = Popen("xrandr", shell=True, stdout=PIPE, stderr=STDOUT)

但是,当按照以下 udev 规则运行时:

ACTION="change", SUBSYSTEM="drm", ENV{HOTPLUG}=="1", RUN+="/usr/local/bin/myscript"

失败,提示 xrandr 返回 1 并显示“无法打开显示”的消息。

有人知道为什么 xrandr 从 udev 规则运行时会失败吗?

完整的脚本,供那些好奇的人参考:

#! /usr/bin/env python3
import os
from subprocess import Popen, PIPE, STDOUT

def log(s):
    home_dir = os.path.expanduser("~")
    #with open (f"{home_dir}/monitor_script.log", "a+") as f:
    with open (f"/home/vedantroy/monitor_script.log", "a+") as f:
        f.write(s)
xrandr = "/usr/bin/xrandr"
xrandr_cmd = Popen(xrandr, shell=True, stdout=PIPE, stderr=STDOUT)
retval = xrandr_cmd.wait()
lines = map(lambda l: l.decode('ascii'), xrandr_cmd.stdout.readlines())
if retval != 0:
    nl = "\n"
    log(f"xrandr returned {retval} with output:\n{nl.join(lines)}")
else:
    layout_cmds = [
        # No monitors plugged in
        f"{xrandr} --auto",
        # Thinkpad T580
        # Monitor plugged into HDMI port
        # Monitor to right of laptop
        f"{xrandr} --output HDMI2 --primary --auto --right-of eDP1"
    ]
    layout = 0
    for line in lines:
        if "HDMI2 connected" in line:
            layout = 1
            break

    layout_cmd_str = layout_cmds[layout]
    layout_cmd = Popen(layout_cmd_str, shell=True)
    retval = layout_cmd.wait()
    if retval != 0:
        log(f"{layout_cmd_str} returnd {retval}")

答案1

udev 无权访问 X,您必须为其提供DISPLAY环境XAUTHORITY变量:

KERNEL=="card0", SUBSYSTEM=="drm", ACTION=="change", ENV{DISPLAY}=":0", ENV{XAUTHORITY}="/home/ben/.Xauthority", RUN+="/bin/bash /path/to/script.sh"

(取自https://frdmtoplay.com/i3-udev-xrandr-hotplugging-output-switching/

.Xauthority当然,你必须调整文件和脚本的路径。

相关内容