为何运行pytest时加-s或--capture=no参数能看到源码的print输出?
为什么pytest用-s或--capture=no能看到print的输出
pytest默认会捕获测试过程中的标准输出(stdout)和标准错误(stderr),目的是让测试结果的输出更干净——只展示测试用例的通过/失败状态,不会被代码里的print()语句打乱输出结构。
-s和--capture=no的核心作用:
-s是--capture=no的简写,两者功能完全一致- 它们会禁用pytest的输出捕获机制,让代码中
print()打印的内容直接输出到控制台,不会被pytest拦截隐藏
拿你给的代码举例:
- src/hello.py代码:
def something(): print('this is a test')
- tests/test_hello.py代码:
from hello import something from unittest import TestCase class need_to_know(TestCase): def test_something(self): something() assert True
默认运行pytest tests/test_hello.py时,控制台只会显示测试通过的结果,看不到this is a test;但如果运行pytest -s tests/test_hello.py或者pytest --capture=no tests/test_hello.py,就能在控制台看到this is a test的输出。
另外提一句:pytest还有其他捕获模式(比如默认的--capture=sys、--capture=fd),但-s是最直接的禁用捕获方式,方便调试时查看print内容。
内容的提问来源于stack exchange,提问作者dataviews
相关产品推荐
相关产品推荐

