Home >Backend Development >Python Tutorial >Can Python Scripts Be Run as Windows Services?

Can Python Scripts Be Run as Windows Services?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 09:44:14260browse

Can Python Scripts Be Run as Windows Services?

Running Python Scripts as Windows Services

In the context of developing a service-based system in Python, the question arises of whether it's possible to run Python scripts as Windows services. This article tackles this query and provides a comprehensive answer.

Indeed, it is feasible to host Python programs as Windows services, leveraging the pythoncom libraries included in ActivePython or via the pywin32 extension. To illustrate this process, consider the following code skeleton for a rudimentary 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)

Insert your custom code into the main() function, typically deploying an infinite loop that can be interrupted by monitoring a flag set in the SvcStop method.

Moreover, Windows is alerted to the existence of your service through the Service Manager. You can monitor and manage it using native Windows utilities like the Services Console (services.msc) or the sc command-line tool. Similar to Unix's /etc/init.d directory for start/stop scripts, Windows uses the scm (Service Control Manager) for managing services. Utilizing the sc utility, you can perform various actions on services, including creating, starting, stopping, and configuring them.

The above is the detailed content of Can Python Scripts Be Run as Windows Services?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn