树莓派如何通过crontab实现SSH式运行获取屏幕分辨率的Python脚本?
问题:Crontab执行调用xrandr的Python脚本失败,SSH运行正常
我有一个用os库调用xrandr获取屏幕分辨率的Python脚本,在SSH环境运行正常,但通过crontab执行时崩溃。
脚本代码
import os screen_resolution = os.popen("xrandr | grep '*' | awk '{print $1}'").read().strip().split("x") screen_width = int(screen_resolution[0]) screen_height = int(screen_resolution[1]) print("Screen Resolution : ", screen_width, "x", screen_height)
尝试过的crontab配置
@reboot python /home/pi/Documents/run.py > /home/pi/log.log 2>&1
(注:原配置末尾多了个t,属于笔误)
或者
@reboot env DISPLAY=:0 XAUTHORITY=~/.Xauthority python /home/pi/Documents/run.py > /home/pi/log.log 2>&1
错误日志
Can't open display Traceback (most recent call last): File "/home/pi/Documents/run.py", line 4, in <module> screen_width = int(screen_resolution[0]) ValueError: invalid literal for int() with base 10: ''
我希望系统完全启动后自动执行脚本,达到手动SSH运行的效果,已经尝试传递DISPLAY和XAUTHORITY变量但无效,该如何解决?
解决方案
1. 修正XAUTHORITY的路径
crontab中~不会被解析为用户家目录,必须使用绝对路径。以pi用户为例,修改crontab配置:
@reboot env DISPLAY=:0 XAUTHORITY=/home/pi/.Xauthority python /home/pi/Documents/run.py > /home/pi/log.log 2>&1
2. 延迟执行脚本
@reboot会在系统启动早期触发,此时X服务可能尚未完全就绪。添加延迟等待X启动完成:
@reboot sleep 30 && env DISPLAY=:0 XAUTHORITY=/home/pi/.Xauthority python /home/pi/Documents/run.py > /home/pi/log.log 2>&1
可根据实际启动速度调整延迟时长(如10/60秒)。
3. 改用无X依赖的分辨率获取方式
如果上述方法仍无效,可直接读取系统硬件文件获取分辨率(适用于树莓派等嵌入式设备),无需依赖X环境:
import os # 读取framebuffer硬件配置文件 with open('/sys/class/graphics/fb0/virtual_size', 'r') as f: res = f.read().strip().split(',') screen_width = int(res[0]) screen_height = int(res[1]) print("Screen Resolution : ", screen_width, "x", screen_height)
这种方式在crontab中直接运行即可,无需额外环境变量。
4. 确认crontab所属用户
确保crontab是pi用户创建的(而非root)。如果使用root的crontab,需切换到pi用户执行:
@reboot su - pi -c "sleep 30 && env DISPLAY=:0 XAUTHORITY=/home/pi/.Xauthority python /home/pi/Documents/run.py > /home/pi/log.log 2>&1"
内容的提问来源于stack exchange,提问作者nozziak
相关产品推荐
相关产品推荐

