通过ubuntu服务使用pyQT4运行python文件时无法连接到Xserver

问题描述

我正在尝试执行使用 PyQT4 的 python 文件

我在服务文件下运行

[Unit]
Description = Test
After=multi-user.target

[Service]
Type=simple
ExecStart = /usr/bin/python3 /home/nvidia/main
Restart=on-abort

[Install]
WantedBy =multi-user.target

文件位于 /lib/systemd/system/test.service 下,我将在 systemctl start Test 之前启动此服务

但启动此服务会导致错误标记cannot connect to X Server,Failed with result exit-code

我正在使用脚本

#!/usr/bin/python

#################################################################################################################################################

# Author          = Rucha
# Version         = V 2.0.3
# Class           = PR01 OOP
# Module          = pyqt4
# Date            = Jan 02 2021

#################################################################################################################################################
import sys
from PyQt4 import QtGui

######################################################################################################################################

class MainWindow:

    def __init__(self):
        self.vBox = QtGui.QHBoxLayout()

    def Title(self,Window,Name):
        Window.setwindowTitle(Name)

    
    def window(self):

        app = QtGui.QApplication(sys.argv)
        w = QtGui.QWidget()

        w.setGeometry(800,800,500,500)

        self.Title(w,"Test")          
        
        w.show()
        sys.exit(app.exec_())
    
MainWindow1 = MainWindow()
MainWindow1.window()

解决方法

通常服务与能够登录/启动 X 环境的普通用户不具有相同的环境。 因此我猜 DISPLAY 没有设置。 在你的服务文件中试试这个,但确保它会在 X 已经运行后启动......

ExecStart = env -i DISPLAY=:0.0 /usr/bin/python3 /home/nvidia/main

示例 - 用户 root 尝试在 X 上运行一些东西 - 有和没有 DISPLAY

#kcalc
qt.qpa.screen: QXcbConnection: Could not connect to display 
Could not connect to any X display.
#env -i DISPLAY=:0.0 kcalc
QStandardPaths: XDG_RUNTIME_DIR not set,defaulting to '/tmp/runtime-root'

您可以在带有和/或不带有 DISPLAY 变量的 XTerm 中进行检查。

,
[Unit]
Description = Test
After=multi-user.target

[Service]
Type=simple
Environment="DISPLAY=:0"
Environment="XAUTHORITY=/home/nvidia/.Xauthority"
ExecStart = /usr/bin/python /home/nvidia/main
Restart=on-failure

[Install]
WantedBy =graphical.target

我使用 systemd 服务使用上述指令值成功执行了 GUI