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

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

最佳答案

打印输出不是来自 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)

关于python - 如何在 Python 中禁用 socketserver 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16501753/

相关文章:

python - 如何在 Python 中重写文本文件

c - 我需要制作一个 C 程序,它接受作为命令行参数传递的整数并打印总和

ruby-on-rails - 工厂女孩 : Automatically assigning parent objects

visual-studio - VS2010 中的单元测试 3.5 项目产生 CS1685 警告

c - 非阻塞标准输出[C/Linux]

linux - 在对话框实用程序中使用 --output-fd 参数

python - R 与 python : why are they different? 中的 ACF 置信区间

python - 如何对混合类型的 Pandas 数据框进行重新采样?

python - 如何制作具有重复值模式的字典?

oracle - 单元测试高度相互依赖的代码