以下摘錄自 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
當然,您必須調整檔案和腳本的路徑。