Search code examples
linuxpyqt4ubuntu-18.04xserver

can not connect to Xserver while running python file using pyQT4 via ubuntu service


I am trying to execute python file which uses PyQT4

I am running below service file

[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

this file is located under /lib/systemd/system/test.service and I am starting this service by systemctl start Test

but starting of this service results in an error tagged cannot connect to X Server, failed with result exit-code

I am using the script

#!/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()

Solution

  • [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
    

    I successfully executed GUI using systemd service using the above directive values