【问题标题】:Python script run with systemd cannot start gedit使用 systemd 运行的 Python 脚本无法启动 gedit
【发布时间】:2019-03-10 10:25:44
【问题描述】:

我在/home/jack/Code/Service/main.py 中有以下 Python 脚本:

from subprocess import Popen

Popen(["/usr/bin/gedit"])

while True:
    pass

我正在使用这个 systemd 服务运行它:

[Unit]
Description=Test

[Service]
Type=simple
Restart=no
User=jack
WorkingDirectory=/home/jack/Code/Service
ExecStart=/usr/bin/python3 main.py

[Install]
WantedBy=multi-user.target

当我使用python3 main.py 从命令行运行main.py 时,它会运行并打开gedit。当我启动 systemd 服务并查看日志时,我看到:

mars 10 11:19:55 Ubuntu-Tower systemd[1]: Started Test.
mars 10 11:19:55 Ubuntu-Tower python3[8827]: Unable to init server: Could not connect: Connection refused
mars 10 11:19:55 Ubuntu-Tower gedit[8835]: cannot open display: 

请注意,gedit 进程实际上确实在服务运行时出现在系统监视器中(并且仅在我停止服务时消失),所以这似乎是一个特定于 GUI 的问题。

发生了什么,我怎样才能得到我想要的行为?

【问题讨论】:

  • 注意:这似乎是与 this 不同的问题,因为我看不出 PATH 或 PYTHONPATH 问题与此处有何关联。
  • 我相信你必须使用After=graphical.target 之类的东西
  • @hansolo 似乎不起作用。我将 After=graphical.target 卡在 [Unit] 部分,但我得到了相同的行为。

标签: python x11 systemd


【解决方案1】:

要在X11、Linux等windows系统中打开窗口,必须指定显示器。通常这是在 DISPLAY 环境变量中定义的。就我而言,它设置为“:0.0”。如果没有设置这个变量,程序不知道在哪里绘制窗口:

marco$ DISPLAY= xeyes
Error: Can't open display:
marco$

某些程序允许您通过-display 参数指定显示。仅此信息是不够的:X11 包含可以连接到特定服务器的允许客户端的访问控制列表。

marco$ su - test
Password:
test$ env | grep DISPLAY
DISPLAY=:0.0
test$ xeyes
No protocol specified
Error: Can't open display: :0.0

xhost是操纵acl的工具:

marco$ xhost +
access control disabled, clients can connect from any host
marco$ su - test
Password:
# disable X11 acl with xhost +
test:~$ xeyes
^C

无论如何请记住,X11 服务器必须正在运行才能打开窗口,如果在服务启动时服务器未在侦听,您可能会引发其他类型的错误(无法初始化服务器:无法连接:连接被拒绝)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2020-10-11
    • 2021-02-13
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多