Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you disable the output of socketserver in Python?

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()
like image 215
mlissner Avatar asked Oct 20 '25 02:10

mlissner


2 Answers

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)
like image 136
jamt Avatar answered Oct 21 '25 17:10

jamt


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)
like image 20
mjv Avatar answered Oct 21 '25 16:10

mjv