14

I have the following simple Threaded fileserver to be used by my application:

class FileServer(Thread):
    """Simple file server exposing the current directory for the thumbnail
    creator
    """

    def __init__(self, port):
        Thread.__init__(self)
        self.port = port

        Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        self.httpd = SocketServer.TCPServer(("", port), Handler)

    def run(self):
        self.httpd.serve_forever()

    def stop(self):
        self.httpd.shutdown()

How can I prevent SimpleHTTPServer to output "GET 'http:// BLA BLA BLA" at every request? Thanks

Imran
  • 87,203
  • 23
  • 98
  • 131
pistacchio
  • 56,889
  • 107
  • 278
  • 420

3 Answers3

30

You can subclass SimpleHTTPServer.SimpleHTTPRequestHandler and override the log_message method. Here is the method you will be overriding, sans docstring:

def log_message(self, format, *args):
    sys.stderr.write("%s - - [%s] %s\n" %
                     (self.address_string(),
                      self.log_date_time_string(),
                      format%args))

So to simply ignore all messages, replace the body of the function with pass. For more fine-grained control (i.e if you still want error messages printed), you may instead override the log_request and/or log_error methods. Original methods are like this:

def log_request(self, code='-', size='-'):
    self.log_message('"%s" %s %s',
                     self.requestline, str(code), str(size))

def log_error(self, format, *args):
    self.log_message(format, *args)

From 2.7 to 3.1 the module names change, but these methods are unchanged.

Lauritz V. Thaulow
  • 49,139
  • 12
  • 73
  • 92
14

Run it this way in Bash:

python -m SimpleHTTPServer &>/dev/null
Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
Ya Zhuang
  • 4,652
  • 31
  • 40
  • 2
    Awesome, now I have this in my `~/.profile`: `alias server="(python -m SimpleHTTPServer > /dev/null 2>&1 &) && echo 'Server running at 0.0.0.0:80' && open http://0.0.0.0:8000"` – Stephen Jul 22 '14 at 21:09
3

There is no need to subclass.

Easier solution:

http_handler = SimpleHTTPServer.SimpleHTTPRequestHandler
http_handler.log_message = lambda a, b, c, d, e: None

Or even a safer way, capture all positional and defaulta arguments

http_handler = SimpleHTTPServer.SimpleHTTPRequestHandler
http_handler.log_message = lambda *args, **kwargs: None

Or even better, as here is clear that we want to ignore the arguments

http_handler.log_message = lambda *_, **__: None
Federico Baù
  • 6,013
  • 5
  • 30
  • 38
Massimo
  • 3,171
  • 3
  • 28
  • 41