如何停止作为Windows服务运行的web.py服务器

时间:2014-10-16 15:23:45

标签: python windows windows-services web.py httpserver

import win32serviceutil
import win32service
import win32event
import thread
import json
import sys
import web
import os
import logging
from ReleaseDistribution.server_actions import Actions
from ReleaseDistribution import logging_setup
import time
from win32api import SetConsoleCtrlHandler
import traceback

class TestHttpService(win32serviceutil.ServiceFramework):
_svc_name_ = "GlobalDeploymentReleaseService"
_svc_display_name_ = "Global Deployment Release Service"

def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__(self,args)
    SetConsoleCtrlHandler(lambda x: True, True)
    self.hWaitStop = win32event.CreateEvent(None,0,0,None)

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

def SvcDoRun(self):

    try:
        app = web.application(urls, globals())
        http_server = web.httpserver.runsimple(app.wsgifunc(), ('0.0.0.0', 8088))
        http_server.run()
    # raise any exceptions, we can't usually recover well
    except Exception as error:
        logger.error('exception...{0}'.format(traceback.format_exc()))
        sys.exit(-1)

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

我是Python和窗口服务api的新手。我需要将python脚本转换为Windows服务。我设法做了第一步,但我找不到阻止它的方法。我得到了“[SC] ControlService FAILED 1061:此时服务无法接受控制消息。”什么时候

我没有无限循环来检查self.run_service标志并调用sys.exit()来终止服务。你能帮助我吗?

1 个答案:

答案 0 :(得分:1)

def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    win32event.SetEvent(self.hWaitStop)
    web.httpserver.server.interrupt = KeyboardInterrupt()

源代码wsgiserver.init.py:start()方法轮询中断,以确定是否停止服务器。

     while self.ready:
        self.tick()
        if self.interrupt:
            while self.interrupt is True:
                # Wait for self.stop() to complete. See _set_interrupt.
                time.sleep(0.1)
            if self.interrupt:
                raise self.interrupt