udev에서 실행할 때 xrandr이 실패함

udev에서 실행할 때 xrandr이 실패함

화면 레이아웃을 감지하고 xrandr을 사용하여 새로 고치기 위한 Python 3 스크립트 "myscript"에서 다음 발췌문은 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을 반환했습니다.

udev 규칙에서 실행할 때 xrandr이 실패하는 이유를 아는 사람이 있습니까?

궁금하신 분들을 위한 전체 스크립트:

#! /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에 액세스할 수 없으므로 DISPLAYXAUTHORITY환경 변수를 제공해야 합니다.

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파일과 스크립트의 경로를 조정해야 합니다.

관련 정보