4

I have socketserver set up to run some unittests, and it's outputting its log to the console.

Is there a way to disable this?

Here's roughly the code I'm running:

class TestServer(SocketServer.TCPServer):
    allow_reuse_address = True


class ScraperExampleTest(unittest.TestCase):
    def setUp(self):
        # Due to requests not supporting the 'file' scheme, we are forced to run
        # our own server. See: https://github.com/kennethreitz/requests/issues/847
        Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        httpd = TestServer(('', PORT), Handler)
        httpd_thread = threading.Thread(target=httpd.serve_forever)
        httpd_thread.setDaemon(True)
        httpd_thread.start()

3 Answers 3

13

The printout doesn't originate from the TCPServer but from the SimpleHTTPRequestHandler, or more precisely it's parent: BaseHTTPRequestHandler. You can change the behaviour by creating your own handler and overloading:

def log_message(self, format, *args)

Something like this should work:

class TestServer(SocketServer.TCPServer):
    allow_reuse_address = True 
    logging = False

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def log_message(self, format, *args):
        if self.server.logging:
            SimpleHTTPServer.SimpleHTTPRequestHandler.log_message(self, format, *args)
Sign up to request clarification or add additional context in comments.

1 Comment

Thsi should be accepted answer. Not only simply works but do it properly, without hacks.
1

A common trick to avoid console output in Python is to redirect it. sys.stdout can be replaced by any open [for writing] text file.

import sys
f = open("myLog.txt", "w")
sto = sys.stdout
sys.stdout = f
#...

#... when done with tests

# restablish the orignal console output
sys.stdout = sto
fclose(f)

3 Comments

I don't love this, but I tried it out by adding sys.stdout = open('/dev/null', 'w') to the setUp method. Didn't change the output at all.
Could it be that the output sent to the console effectively comes from writes to stderr rather than stdout? Try redirecting stderr as well.
Redirecting stderr works, but it's so much of a hack that I can't endorse it. If the tests fail, I'll get no output. That's worse than too much output during success.
0

Not the neatest solution but you can also override the function in the main library:

import http.server

if not debug:                               

    http.server.SimpleHTTPRequestHandler.log_message = lambda *args: None

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.