Python HTTP Server 无法在 Windows 服务中发送响应 [英] Python HTTP Server unable to send response inside Windows Service

查看:35
本文介绍了Python HTTP Server 无法在 Windows 服务中发送响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个简单的 HTTP 服务器并使用 pywin32 将它变成了一个 Windows 服务.服务器在调试器中运行时成功处理请求,在实际服务中它获取请求但挂起 send_response 操作.可能是什么原因?

I've written a simple HTTP server and made it into a Windows service using pywin32. The server successfully processes requests when run in the debugger, inside actual service it gets the request but hangs on send_response operation. What might be the reason?

from http.server import BaseHTTPRequestHandler, HTTPServer
import win32serviceutil
import win32service
import sys

PORT_NUMBER = 6363

class myHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(bytes("Hello World !", "utf-8"))
        return

class TestSvc(win32serviceutil.ServiceFramework):
    _svc_name_ = "TestSvc"
    _svc_display_name_ = "Test Service"
    _svc_description_ = "Tests server inside service."

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.server = HTTPServer(('', PORT_NUMBER), myHandler)

    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        print('Started httpserver on port ', PORT_NUMBER)
        self.server.serve_forever()

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.server.shutdown()

#sys.frozen = 'windows_exe'
if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(TestSvc, argv=sys.argv)

推荐答案

实际上是在执行 sys.stderr.write(这是 BaseHTTPRequestHandler 的默认日志输出)时挂起的.所以我在我的请求处理程序类中覆盖了 log_message 函数,现在它工作正常.

Actually it was hanging when executing sys.stderr.write (which is the default logging output for BaseHTTPRequestHandler). So I've overridden log_message function in my request handler class and it works fine now.

这篇关于Python HTTP Server 无法在 Windows 服务中发送响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆