The following excerpt from a Python 3 script "myscript" that is meant to detect the screen layout and refresh it using xrandr works fine when run with sudo /usr/local/bin/myscript
or /usr/local/bin/myscript
:
xrandr_cmd = Popen("xrandr", shell=True, stdout=PIPE, stderr=STDOUT)
However, when run as a result of the following udev rule:
ACTION="change", SUBSYSTEM="drm", ENV{HOTPLUG}=="1", RUN+="/usr/local/bin/myscript"
it fails, stating that xrandr has returned 1 with the message "Can't open display".
Does anyone know why xrandr would fail when run from a udev rule?
The full script, for those who are curious:
#! /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}")
udev does not have access to X, you have to give it the
DISPLAY
andXAUTHORITY
environment variable:(Taken from https://frdmtoplay.com/i3-udev-xrandr-hotplugging-output-switching/ )
Of course, you have to adjust the path to the
.Xauthority
file and the script.