2015-12-27 24 views
1

我有一個實現Python腳本內置Web服務器:Python的BaseHTTPServer - 防止錯誤(「連接重置由對等」等),從破壞詛咒顯示

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 traceback會在我的不錯的curses顯示中濺起。

我已經嘗試在我的BaseHTTPRequestHandler類的do_GET部分周圍添加try...exception塊,但沒有任何效果。

如何在此代碼中使Python追蹤消息保持沉默?

回答

1

嘗試重寫的BaseServerhandle_error方法:

class MyServer(SocketServer.TCPServer): 

    def handle_error(self, request, client_address): 
     pass 

start_server函數然後使用MyServer

+0

謝謝,這似乎已經做到了! –

相關問題