有时我想在我的代码中插入一些打印语句,看看当我执行它时会打印出什么。我通常使用现有的pytest测试来“锻炼”它。但是当我运行这些时,我似乎无法看到任何标准输出(至少在我的IDE PyCharm中)。
是否有一种简单的方法可以在pytest运行期间查看标准输出?
有时我想在我的代码中插入一些打印语句,看看当我执行它时会打印出什么。我通常使用现有的pytest测试来“锻炼”它。但是当我运行这些时,我似乎无法看到任何标准输出(至少在我的IDE PyCharm中)。
是否有一种简单的方法可以在pytest运行期间查看标准输出?
当前回答
根据pytest文档,版本3的pytest可以在测试中临时禁用捕获:
def test_disabling_capturing(capsys):
print('this output is captured')
with capsys.disabled():
print('output not captured, going directly to sys.stdout')
print('this output is also captured')
其他回答
-s开关禁用每个测试捕获(仅当测试失败时)。
-s等价于——capture=no。
根据pytest文档,版本3的pytest可以在测试中临时禁用捕获:
def test_disabling_capturing(capsys):
print('this output is captured')
with capsys.disabled():
print('output not captured, going directly to sys.stdout')
print('this output is also captured')
运行测试时使用-s选项。当运行测试时,exampletest.py中的所有打印语句都将被打印到控制台上。
py.test exampletest.py -s
如果有人想从输出代码中运行测试:
if __name__ == '__main__':
pytest.main(['--capture=no'])
我建议使用-h命令。可以使用一些非常有趣的命令。 但是,对于这个特殊的情况:-s快捷方式——capture=no。就足够了
pytest <test_file.py> -s