可以作为服务运行的 Python 脚本

本示例中使用的模块是 pywin32 (Python for Windows 扩展)的一部分。根据你安装 Python 的方式,你可能需要单独安装。

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)

这只是样板。你的应用程序代码(可能调用单独的脚本)将放在 main() 函数中。

你还需要将其安装为服务。目前最好的解决方案似乎是使用非吸吮服务管理器 。这允许你安装服务并提供用于配置服务执行的命令行的 GUI。对于 Python,你可以这样做,一次创建服务:

nssm install MyServiceName c:\python27\python.exe c:\temp\myscript.py

其中 my_script.py 是上面的样板脚本,修改为在 main() 函数中调用应用程序脚本或代码。请注意,该服务不直接运行 Python 脚本,它运行 Python 解释器并在命令行上传递主脚本。

或者,你可以使用 Windows Server Resource Kit 中提供的工具来获取操作系统版本,以便创建服务。