3

我设置了 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()
4

2 回答 2

10

打印输出不是来自 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)
于 2014-08-14T15:09:45.000 回答
1

在 Python 中避免控制台输出的一个常见技巧是重定向它。sys.stdout 可以替换为任何打开的 [for writing] 文本文件。

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)
于 2013-05-11T21:23:11.627 回答