Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从pytest.main()输出stdio和stderr_Python_Pytest - Fatal编程技术网

Python 从pytest.main()输出stdio和stderr

Python 从pytest.main()输出stdio和stderr,python,pytest,Python,Pytest,有没有一种方法可以通过调用main通过pytest来获取测试的输出 string = "-x mytests.py" pytest.main(string) print(????????) 如果这是一个进程,我可以使用communicate()获得输出,但在Python3中作为函数运行pytest时,我找不到与之等效的pytest,而不是在终端中作为独立运行pytest 编辑: 我确实尝试过使用sys.stdout,但它也不起作用……我基本上被卡住了,因为我无法以任何方式获得pytest输出;

有没有一种方法可以通过调用main通过pytest来获取测试的输出

string = "-x mytests.py"
pytest.main(string)
print(????????)
如果这是一个进程,我可以使用
communicate()
获得输出,但在Python3中作为函数运行pytest时,我找不到与之等效的pytest,而不是在终端中作为独立运行pytest

编辑:
我确实尝试过使用
sys.stdout
,但它也不起作用……我基本上被卡住了,因为我无法以任何方式获得pytest输出;在我的输出IDE窗口的旁边。任何建议或解决方法都将不胜感激。

由于一个不同的问题找到了答案,该问题提到了如何重定向整个
标准输出流

我没有找到只打印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(per)开始,有一种更简单的方法来完成您的任务:

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())