I use this context manager to capture output. It ultimately uses the same technique as some of the other answers by temporarily replacing sys.stdout. I prefer the context manager because it wraps all the bookkeeping into a single function, so I don't have to re-write any try-finally code, and I don't have to write setup and teardown functions just for this.import sysfrom contextlib import contextmanagerfrom StringIO import StringIO@contextmanagerdef captured_output(): new_out, new_err = StringIO(), StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = new_out, new_err yield sys.stdout, sys.stderr finally: sys.stdout, sys.stderr = old_out, old_err像这样使用它:with captured_output() as (out, err): foo()# This can go inside or outside the `with` blockoutput = out.getvalue().strip()self.assertEqual(output, 'hello world!')此外,由于在退出 with 块时恢复了原始输出状态,我们可以在与第一个捕获块相同的功能中设置第二个捕获块,这是使用 setup 和拆卸功能,并在手动编写 try-finally 块时变得冗长.当测试的目标是比较两个函数的结果而不是某个预先计算的值时,这种能力就派上用场了.Furthermore, since the original output state is restored upon exiting the with block, we can set up a second capture block in the same function as the first one, which isn't possible using setup and teardown functions, and gets wordy when writing try-finally blocks manually. That ability came in handy when the goal of a test was to compare the results of two functions relative to each other rather than to some precomputed value. 这篇关于如何在python中使用nosetest/unittest断言输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-30 12:08