如何将 pytest.main 消息写入字符串?

How can I write the pytest.main messages into a string?

当我在Python中调用pytest.main(...)时,它会在输出window中显示单元测试消息,例如

============================= test session starts =============================
platform win32 -- Python 3.6.4, pytest-3.3.2, py-1.5.2, pluggy-0.6.0
rootdir: xxx, inifile: pytest.ini
plugins: cov-2.5.1, hypothesis-3.38.5
collected 1 item

..\test_example.py F                                      [100%]

================================== FAILURES ===================================
_______________________________ test_something ________________________________

    def test_something():
>       assert 1 == 0
E       assert 1 == 0

..\test_example.py:5: AssertionError
========================== 1 failed in 0.60 seconds ===========================

我的问题很简单,我怎样才能将上面的消息放入一个字符串对象中。文档对此没有任何说明。而 what pytest.main() returns 只是一个表示错误代码的整数。

https://docs.pytest.org/en/latest/usage.html#calling-pytest-from-python-code

我不知道 pytest,但您可以尝试将标准输出重定向到文件。像这样:

import sys
sys.stdout = open("log.txt", "w")

之后您可以读取文件以获取字符串。你想用这些字符串做什么?