使用pyautogui+pyvirtualdisplay远程无显示UI测试遇.Xauthority错误
远程无显示环境下UI测试的XauthError问题解决方案
问题场景
使用PyAutoGUI结合PyVirtualDisplay在远程服务器(无显示环境)执行UI测试,测试代码如下:
import os import pyautogui import Xlib.display from easyprocess import EasyProcess from pyvirtualdisplay.smartdisplay import SmartDisplay import cv2 import sys python = sys.executable window_width = 1200 window_height = 800 # PyVirtualDisplay display = SmartDisplay(visible=False, size=(window_width, window_height)) display.start() # PyAutoGUI pyautogui._pyautogui_x11._display = Xlib.display.Display(os.environ['DISPLAY']) # Do your thing pyautogui_window_width, pyautogui_window_height = pyautogui.size() print("Screen size: {}x{}".format(pyautogui_window_width, pyautogui_window_height)) p = EasyProcess([python, 'script.py']) p.start() p.sleep(1) x, y = pyautogui.locateCenterOnScreen(image='g.png', confidence=0.9) print(x, y) pyautogui.moveTo(x, y) pyautogui.click() p.stop() display.stop() print('>>> All done.')
运行时触发以下错误:
raise error.XauthError('~/.Xauthority: %s' % err) Xlib.error.XauthError: ~/.Xauthority: [Errno 2] No such file or directory: '/home/gitlab-runner/.Xauthority'
解决方案
1. 手动创建并配置Xauthority文件
针对运行脚本的用户(此处为gitlab-runner),执行以下命令创建缺失的认证文件并设置正确权限:
touch /home/gitlab-runner/.Xauthority chmod 600 /home/gitlab-runner/.Xauthority
Xlib依赖该文件完成X服务器的身份认证,必须确保文件仅对所有者可读可写。
2. 让PyVirtualDisplay自动处理Xauth认证
修改代码中创建虚拟显示的部分,启用use_xauth参数(需PyVirtualDisplay版本支持),同时显式指定Xauthority路径:
os.environ['XAUTHORITY'] = '/home/gitlab-runner/.Xauthority' display = SmartDisplay(visible=False, size=(window_width, window_height), use_xauth=True)
3. 用xvfb-run直接包装脚本(最简方案)
无需修改代码,直接用xvfb-run命令启动测试脚本,它会自动创建虚拟显示并处理所有认证逻辑:
xvfb-run -a -s "-screen 0 1200x800x24" python your_test_script.py
参数说明:
-a:自动寻找可用的显示编号-s "-screen 0 1200x800x24":指定虚拟屏幕的分辨率和色深
4. 移除冗余的PyAutoGUI显示绑定
PyVirtualDisplay启动后会自动设置DISPLAY环境变量,PyAutoGUI会自动读取该变量,因此可以删除以下冗余代码:
pyautogui._pyautogui_x11._display = Xlib.display.Display(os.environ['DISPLAY'])
优化后的完整测试代码
import os import pyautogui from easyprocess import EasyProcess from pyvirtualdisplay.smartdisplay import SmartDisplay import cv2 import sys python = sys.executable window_width = 1200 window_height = 800 # 配置Xauthority路径 os.environ['XAUTHORITY'] = '/home/gitlab-runner/.Xauthority' # 启动带Xauth支持的虚拟显示 display = SmartDisplay(visible=False, size=(window_width, window_height), use_xauth=True) display.start() # 获取屏幕尺寸 pyautogui_window_width, pyautogui_window_height = pyautogui.size() print("Screen size: {}x{}".format(pyautogui_window_width, pyautogui_window_height)) p = EasyProcess([python, 'script.py']) p.start() p.sleep(1) # 建议使用g.png的绝对路径避免找不到文件 x, y = pyautogui.locateCenterOnScreen(image='g.png', confidence=0.9) print(x, y) pyautogui.moveTo(x, y) pyautogui.click() p.stop() display.stop() print('>>> All done.')
内容的提问来源于stack exchange,提问作者Jerin Antony
相关产品推荐
相关产品推荐

