[英]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. 我已经设置了socketserver来运行一些单元测试,并且它将日志输出到控制台。
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()
The printout doesn't originate from the TCPServer but from the SimpleHTTPRequestHandler, or more precisely it's parent: BaseHTTPRequestHandler. 打印输出不是源自TCPServer,而是源自SimpleHTTPRequestHandler,或更确切地说,它是父级: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)
A common trick to avoid console output in Python is to redirect it. 避免在Python中控制台输出的常见技巧是重定向它。 sys.stdout can be replaced by any open [for writing] text file.
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.