Python BaseHTTPServer - 防止错误("connection reset by peer," 等)破坏 curses 显示
Python BaseHTTPServer - prevent errors ("connection reset by peer," etc.) from ruining curses display
我有一个 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 服务器中发生错误时(例如 "connection reset by peer" 等),指示所述错误的 python 回溯会散布在我漂亮的 curses 显示中。
我尝试在 BaseHTTPRequestHandler
class 的 do_GET
部分周围添加 try...exception
块,但没有效果。
如何在这段代码中隐藏 Python 回溯消息?
尝试覆盖 BaseServer
的 handle_error
方法:
class MyServer(SocketServer.TCPServer):
def handle_error(self, request, client_address):
pass
然后在 start_server
函数中使用 MyServer
。
我有一个 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 服务器中发生错误时(例如 "connection reset by peer" 等),指示所述错误的 python 回溯会散布在我漂亮的 curses 显示中。
我尝试在 BaseHTTPRequestHandler
class 的 do_GET
部分周围添加 try...exception
块,但没有效果。
如何在这段代码中隐藏 Python 回溯消息?
尝试覆盖 BaseServer
的 handle_error
方法:
class MyServer(SocketServer.TCPServer):
def handle_error(self, request, client_address):
pass
然后在 start_server
函数中使用 MyServer
。