从 pytest.main() 输出 stdio 和 stderr

6 python pytest

有没有办法使用对 main 的调用从您通过 pytest 运行的测试中获取输出?

string = "-x mytests.py"
pytest.main(string)
print(????????)
Run Code Online (Sandbox Code Playgroud)

如果这是一个进程,我可以使用communicate()它来获取输出,但是在从 Python3 将其作为函数运行时,我找不到 pytest 的等效项,而不是从终端独立运行它。

编辑:我确实尝试使用,sys.stdout但它也不起作用......我从根本上陷入困境,因为我无法以任何方式获得 pytest 输出;在我的输出 IDE 窗口旁边。任何建议或解决方法将不胜感激。

小智 4

由于另一个问题找到了答案,该问题提到了如何重定向整个stdout流。

我没有找到只打印 pytest 消息的方法;但我可以通过以下方式将 stdio 从屏幕上的输出重定向到字符串变量:

import sys
from io import StringIO

def myfunctionThatDoesSomething():

    # Save the original stream output, the console basically
    original_output = sys.stdout
    # Assign StringIO so the output is not sent anymore to the console
    sys.stdout = StringIO()
    # Run your Pytest test
    pytest.main(script_name)
    output = sys.stdout.getvalue()
    # close the stream and reset stdout to the original value (console)
    sys.stdout.close()
    sys.stdout = original_output

    # Do whatever you want with the output
    print(output.upper())
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助任何寻找从 pytest 输出中检索数据的方法的人,同时找到更好的解决方案来获取变量中的 pytest 输出。