Search code examples
pythonwindowsservicewindows-services

Run Python script with parameter as Windows Service


I created a Windows Service with python. It works well when I run it with debug mode, but when I start the service it doesn't work. This is the sample of my script:

def run(param):
    subprocess.Popen(["C:\\SER\\txt_write.pyw",param], shell=True)
#txt_write is a simple script: put the parameter into b.txt

def add_param():
    x="123456"
    run(x)

class PythonCornerExample(SMWinservice):
    _svc_name_ = "name"
    _svc_display_name_ = "name disp"
    _svc_description_ = "desc"

    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):
        i=0
        while self.isrunning:
            add_param()
            f= open("C:\\SER\\a.txt","a+")
            f.write("xyz")
            f.close()
            
            time.sleep(25)

if __name__ == '__main__':
    PythonCornerExample.parse_command_line()

So, when I run this script in debug mode it put "xyz" text into a.txt, and calls another python script, that put the parameter (123456) into b.txt. This is how I want it to works.

My problem is, installed as Windows Service the a.txt works, but b.txt doesn't.

What is wrong with my script? Why is it OK in debug mode, and why is it wrong as Services?


Solution

  • change last 2 lines with bellow code:

    import servicemanager, sys
    if __name__ == '__main__':
      if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(PythonCornerExample)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        PythonCornerExample.parse_command_line()