72

I am writing a simple http server as part of my project. Below is a skeleton of my script:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class MyHanlder(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write('<html><body><p>OK</p></body></html>')

httpd = HTTPServer(('', 8001), MyHanlder)
httpd.serve_forever()

My question: how do I suppress the stderr log output my script produces every time a client connects to my server?

I have looked at the HTTPServer class up to its parent, but was unable to find any flag or function call to achieve this. I also looked at the BaseHTTPRequestHandler class, but could not find a clue. I am sure there must be a way. If you do, please share with me and others; I appreciate your effort.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93

1 Answers1

154

This will probably do it:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write('<html><body><p>OK</p></body></html>')
    def log_message(self, format, *args):
        return

httpd = HTTPServer(('', 8001), MyHandler)
httpd.serve_forever()
MattH
  • 37,273
  • 11
  • 82
  • 84
  • This gave me such a headache because my httpserver wasn't returning anything when I ran it in the background without a tty. You are a life saver. Thanks! – agressen Apr 29 '15 at 07:41
  • @agressen, same frustration here -- and same thanks to MattH. My app is implemented as a `.pyw` because it's a Tkinter interface, so not having a console window was preventing any replies from being sent. – JDM Jan 02 '20 at 17:05
  • 4
    you probably want to override `log_request` instead of `log_message`, since the latter is used for other types of logging including errros. – ealfonso Sep 21 '20 at 04:50
  • 1
    Thanks for the hint, which leads me to this [official doc](https://docs.python.org/3/library/http.server.html#http.server.BaseHTTPRequestHandler.log_message) – RayLuo Dec 04 '20 at 06:54
  • 1
    Note that if you still want to see errors (which you usually do), you can instead override the `log_request` function instead, as `def log_request(self, code='-', size='-'): return`. – Mike 'Pomax' Kamermans Nov 15 '22 at 17:38
  • took me a while to notice the difference – uranix Jan 21 '23 at 15:54