You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Docker容器中运行PyAutoGUI脚本控制主机触摸屏时的X11连接问题求助

在Docker容器中运行PyAutoGUI脚本控制主机触摸屏时的X11连接问题求助

大家好,我这边遇到个棘手的问题想请教下:

我们工作环境是用Docker容器在一台带触摸屏的定制Linux机器上运行脚本,我作为QA想写自动化测试来模拟触摸屏的点击操作。

麻烦的点在于这台Linux机器只有基础包,安装新包特别麻烦,而且为了不搞乱主机系统,我也希望把自动化脚本放在Docker容器里跑,这样也方便我测试不同的依赖包。

我打算用PyAutoGUI来模拟触摸屏输入(我知道这事没听起来那么简单),但现在卡在了让Docker容器访问主机屏幕这一步。跑简单测试脚本的时候,一直报这两个错误:

Traceback (most recent call last):

File "/usr/local/lib/python3.12/site-packages/Xlib/support/unix_connect.py", line 76, in get_socket

s.connect('/tmp/.X11-unix/X%d' % dno)

ConnectionRefusedError: [Errno 111] Connection refused

Xlib.error.DisplayConnectionError: Can't connect to display ":0": [Errno 111] Connection refused

我知道问题出在X11的权限限制上,也试了网上找的各种办法,但都没解决。本来打算深入学习下X11的工作原理,但这可能要花不少时间,所以想问问有没有现成的解决方案,或者更好的实现思路?另外如果我在术语上有混淆的地方,也请大家指正。

下面是我现在用的Dockerfile和docker-compose.yaml,里面很多内容都是我试的各种方案,所以看起来有点乱,先抱歉了:

我的Dockerfile

FROM ubuntu:latest as notebook

WORKDIR /automation_test

COPY /src /automation_test/src

RUN apt update && apt-get update

RUN apt -y install python3 python3-pip

RUN pip install --upgrade pip

RUN pip install -r src/requirements.txt

RUN apt-get -y install -y wget

RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list

RUN apt-get update && apt-get -y install google-chrome-stable

RUN apt-get -y install x11-apps

RUN apt-get -y install xauth

RUN apt-get -y install openbox

RUN mkdir /root/.Xauthority

RUN HOST=cctv

RUN DISPLAY_NUMBER=$(echo $DISPLAY | cut -d. -f1 | cut -d: -f2)

RUN AUTH_COOKIE=$(xauth list | grep "$(hostname)/unix:${DISPLAY_NUMBER} " | awk '{print $3}')

RUN xauth add ${HOST}/unix: ${DISPLAY_NUMBER} MIT-MAGIC-COOKIE-1 ${AUTH_COOKIE}

...

我的docker-compose.yaml

version: '3.6'

x-base: &base
  ipc: host
  pid: host
  privileged: true
  network_mode: host
  volumes:
    - ./src/results:/automation_test/src/results
    - ./src/tmp:/automation_test/src/tmp
    - /tmp/.X11-unix:/tmp/.X11-unix
  environment:
    - DISPLAY=${DISPLAY}
  extra_hosts:
    - "host.docker.internal:host-gateway"

services:
  notebook:
    <<: *base
    image: notebook
    container_name: notebook
    build:
      context: .
      target: notebook
    command: ["/bin/bash"]

另外提一句,我现在用的是Ubuntu基础镜像,之后打算换成纯Python镜像来精简。

备注:内容来源于stack exchange,提问作者The Nerdly Gentleman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 10:23:13