有时我想在我的代码中插入一些打印语句,看看当我执行它时会打印出什么。我通常使用现有的pytest测试来“锻炼”它。但是当我运行这些时,我似乎无法看到任何标准输出(至少在我的IDE PyCharm中)。

是否有一种简单的方法可以在pytest运行期间查看标准输出?


当前回答

pytest test_name.py -v -s

简单!

其他回答

我建议使用-h命令。可以使用一些非常有趣的命令。 但是,对于这个特殊的情况:-s快捷方式——capture=no。就足够了

pytest <test_file.py> -s

如果有人想从输出代码中运行测试:

if __name__ == '__main__':
    pytest.main(['--capture=no'])
pytest test_name.py -v -s

简单!

如果使用日志记录,除了通用标准输出的-s外,还需要指定打开日志记录输出。基于pytest测试中的日志记录,我使用:

pytest——log-cli-level=DEBUG -s my_directory/

根据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')