如何在Python中禁用socketserver的输出?

时间:2013-05-11 21:09:41

标签: python unit-testing stdout socketserver

我设置了socketserver来运行一些单元测试,并将其日志输出到控制台。

有没有办法禁用它?

以下是我正在运行的代码:

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()

2 个答案:

答案 0 :(得分:5)

打印输出不是来自TCPServer,而是来自SimpleHTTPRequestHandler,或者更确切地说来自它的父级:BaseHTTPRequestHandler。您可以通过创建自己的处理程序和重载来更改行为:

def log_message(self, format, *args)

这样的事情应该有效:

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)

答案 1 :(得分:1)

在Python中避免控制台输出的常见技巧是重定向它。 sys.stdout可以被任何打开的[用于写入]文本文件替换。

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)