如何使用 Python 创建 windows 服务

How to create windows service using Python

我写了一个 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)

我有 运行 命令 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.

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

> 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.

不确定为什么它没有 运行ning,在调试模式下它 运行 没问题。请帮忙。

任何遇到这个问题的人,只需复制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