从 pytest.main() 输出 stdio 和 stderr

Output stdio and stderr from pytest.main()

有没有一种方法可以通过调用 main 通过 pytest 运行 从测试中获取输出?

string = "-x mytests.py"
pytest.main(string)
print(????????)

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

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

找到了另一个问题的答案,该问题提到了如何重定向整个 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())

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

从 Python 3.4 开始(根据 the docs),有一种更简单的方法可以完成您正在尝试做的事情:

from io import StringIO
from contextlib import redirect_stdout

temp_stdout = StringIO()
with redirect_stdout(temp_stdout):
    result = pytest.main(sys.argv)
stdout_str = temp_stdout.getvalue()
# or whatever you want to do with it
print(stdout_str.upper())