gpt4 book ai didi

Python BaseHTTPServer - 防止错误 ("connection reset by peer,"等)破坏诅咒显示

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:07 25 4
gpt4 key购买 nike

我有一个实现内置 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 回溯消息?

最佳答案

尝试重写BaseServerhandle_error方法:

class MyServer(SocketServer.TCPServer):

def handle_error(self, request, client_address):
pass

然后在 start_server 函数中使用 MyServer

关于Python BaseHTTPServer - 防止错误 ("connection reset by peer,"等)破坏诅咒显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34485696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com