在Ubuntu 18.04上将Python GUI应用程序作为服务运行

0 投票
1 回答
1310 浏览
提问于 2025-06-18 04:11

我成功地在树莓派上把我的图形界面Python应用程序作为服务运行了。使用的单元文件是:

[Unit]
Description=Example systemd service.
After=graphical.target

[Service]
Type=simple
Environment="Display=:0"
Environment=XAUTHORITY=/home/pi/.Xauthority
WorkingDirectory=/home/pi/tf/
ExecStart=/home/pi/tf/myApp.py
Restart=always
RestartSec=10s
KillMode=process
Timeout=infinity

[Install]
WantedBy=graphical.target

在我的Python应用程序开始时,我添加了python3的路径,像这样:

#! /address/where/is/python3

但是在Ubuntu上我无法做到这一点。

我觉得可能是因为没有.Xauthority文件。 在Ubuntu上我运行了:

echo $XAUTHORITY

然后我得到了:

/run/user/1000/Xauthority

接着我修改了这些行:

Environment=XAUTHORITY=/run/user/1000/Xauthority
WorkingDirectory=/home/sergio/tf/
ExecStart=/home/sergio/tf/myApp.py

使用“journalctl -u myApp -f”显示了以下错误:

cannot connect to X server

有没有人知道这可能是什么问题?

相关问题:

  • 暂无相关问题
暂无标签

1 个回答

0

我通过按照htorque在这篇帖子中的步骤解决了这个问题,帖子链接在这里:https://askubuntu.com/questions/21923/how-do-i-create-the-xauthority-file

步骤如下:

1- 打开系统 > 偏好设置 > 启动应用程序

2- 点击“添加”:

3- 名称:Xauthority

4- 命令:/bin/bash -c 'ln -s -f "$XAUTHORITY" ~/.Xauthority' 注释:这个命令会创建一个从 ~/.Xauthority 到 $XAUTHORITY 的符号链接,然后点击“添加”来保存这个设置。

现在每次你登录的时候,它都会自动创建一个指向当前授权文件的链接。

所以现在我们在 ~/ 目录下有了 .Xauthority 文件。最后,服务文件 myApp.service 更新成了这样:

Environment="Display=:0" Environment=XAUTHORITY=/home/"yourUsername"/.Xauthority

撰写回答