如何使用Python创建Windows服务

S A*_*rew 6 python windows-services pywin32

我编写了一个 python 脚本,它将作为 Windows 服务安装。下面是代码:

import datetime
import logging
from logging.handlers import RotatingFileHandler
import os
import time
from random import randint
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


def setup_logger(logger_name, log_file, level=logging.ERROR):
    log_formatter = logging.Formatter('%(asctime)s %(message)s')
    my_handler = RotatingFileHandler(log_file, maxBytes=100 * 1024 * 1024, backupCount=5)
    my_handler.setFormatter(log_formatter)
    my_handler.setLevel(level)
    l = logging.getLogger(logger_name)
    l.handlers[:] = []
    l.addHandler(my_handler)


curr_path = os.getcwd()
log_file = "F:\\Projects\\TestService\\logs\\application.log"
setup_logger('debug', log_file)
log = logging.getLogger('debug')

class AppServerSvc(win32serviceutil.ServiceFramework):
    _svc_name_ = "test_service"
    _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)
        self.isrunning = False

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

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

    def main(self):
        while self.isrunning:
            log.error("Running {}".format(randint(00, 99)))
            time.sleep(10)


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)
Run Code Online (Sandbox Code Playgroud)

我已运行命令python test_service.py install来安装服务并获得了正确的输出Installing service test_service Service installed。当我打开服务选项卡时,我可以看到那里列出了我的服务。当我单击启动服务时,出现以下错误:

在此输入图像描述

谁能告诉我代码中有什么问题导致它无法启动服务。请帮忙。谢谢

更新:

我在调试模式下运行该服务cmd,看起来工作正常。但从服务选项卡来看,它不起作用并显示上述错误。

> python test_service.py debug
      Debugging service test_service - press Ctrl+C to stop.
      Info 0x40001002 - The test_service service has started.
Run Code Online (Sandbox Code Playgroud)

启动服务时,出现同样的错误:

> python test_service.py start
     Starting service test_service
     Error starting service: The service did not respond to the start or control request in a timely fashion.
Run Code Online (Sandbox Code Playgroud)

不知道为什么它没有运行,在调试模式下它运行良好。请帮忙。

S A*_*rew 6

任何遇到此问题的人,只需复制pywintypes36.dll

Python36\Lib\site-packages\pywin32_system32

Python36\Lib\site-packages\win32

有用的命令:

  1. 安装服务:python app.py install

  2. 卸载服务:python app.py remove

  3. 启动服务:python app.py start

  4. 更新服务:python app.py update