代码之家  ›  专栏  ›  技术社区  ›  Donald Burr

Python BaseHTTPServer-防止错误(“对等方重置连接”等)破坏诅咒显示

  •  1
  • Donald Burr  · 技术社区  · 9 年前

    我有一个实现内置web服务器的Python脚本:

    class http_server(BaseHTTPRequestHandler):
        def log_message(self, format, *args):
          # prevent the BaseHTTPServer log messages, we use our own logging instead
          return
        def do_GET(self):
          log("responding to http request from %s: %s" % (self.client_address[0], self.path))
          text_string = "Hello World"
          self.send_response(200)
          self.send_header("Content-type", "text/plain")
          self.send_header("Content-Length", len(text_string))
          self.end_headers()
          self.wfile.write(text_string)
    
    def start_server():
      try:
        httpd = SocketServer.TCPServer(("", 8888), http_server)
        httpd.serve_forever()
      except Exception as e:
          cleanup(None, None)
          print "Error starting internal http server: %s" % repr(e)
          sys.exit(1)
    
    # main script
    # does various things, initializes curses, etc.
    start_server()
    

    这很好,但问题是python脚本还使用在另一个线程中运行的curses实现了屏幕上的状态显示。当HTTP服务器中发生错误(例如“对等方重置连接”等)时,指示所述错误的python回溯会在我漂亮的诅咒显示屏上飞溅。

    我已尝试添加 try...exception 周围的街区 do_GET 我的一部分 BaseHTTPRequestHandler 但这没有效果。

    我如何在这段代码中静默Python回溯消息?

    1 回复  |  直到 9 年前
        1
  •  2
  •   John Keyes    9 年前

    尝试重写 handle_error 方法 BaseServer :

    class MyServer(SocketServer.TCPServer):
    
        def handle_error(self, request, client_address):
            pass
    

    然后使用 MyServer 在您的 start_server 作用