How to Run a Python Script as a Service in Windows

How do you run a Python script as a service in Windows?

Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).

This is a basic skeleton for a simple service:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"

def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)

def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()

def main(self):
pass

if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)

Your code would go in the main() method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop method

Run Python script as a windows service

Just a few days back I have successfully sorted out my issue I just made some changes to my code and it started working properly. I am only posting these answers for someone like me who got this issue in the future he can easily sort it out.
This is the new code:

def WriteToFile():

while True:
file = open ( "C:\\file.txt" , "w" )
now = datetime.now()
now = now.strftime("%B %d, %y %H:%M:%S")
file.write(now)

class Pythonservice(win32serviceutil.ServiceFramework):


_svc_name_ = 'PC-Service'
_svc_display_name_ = 'PC-Service'
_svc_description_ = 'Freindly Service'

@classmethod
def parse_command_line(cls):

win32serviceutil.HandleCommandLine(cls)

def __init__(self, args):

win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)

def SvcStop(self):

self.stop()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)

def SvcDoRun(self):

self.start()
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))
self.main()

def start(self):
self.isrunning = True

def stop(self):
self.isrunning = False

def main(self):
WriteToFile()



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

After these changes, I opened up a command prompt as administrator and type this command to install my service.

C:\wamp64\www\project\python\New folder>python testing.py install

I got the success message. After successful installation, I started my service using this command

C:\wamp64\www\project\python\New folder>python testing.py start

and service started successfully I confirmed from service manager as well whether my service is running or not and it was running after restarting my pc service was still in running state.

Run Python script with parameter as Windows Service

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()

How to create windows service using Python

Anyone facing this issue, just copy pywintypes36.dll

from Python36\Lib\site-packages\pywin32_system32

to Python36\Lib\site-packages\win32

Helpful commands:

  1. Install a service: python app.py install

  2. Uninstall a service: python app.py remove

  3. Start a service: python app.py start

  4. Update service: python app.py update

Run python script as a service on Windows with an interface

I guess that I already had my answer, when I asked this question. So without writing a server/client interface, I have to live with my log-files. Acknowledgements for the guidance in the comments.



Related Topics



Leave a reply



Submit