使用pytest和xdist时如何打印输出

How to print output when using pytest with xdist

我正在使用py.test来运行测试。 我正在使用它与pytest-xdist并行运行测试。 我想在我的测试中看到print语句的输出。

我有:Ubuntu 15.10,Python 2.7.10,pytest-2.9.1,pluggy-0.3.1。

这是我的测试文件:

1
2
3
4
5
6
def test_a():
    print 'test_a'


def test_b():
    print 'test_b'

当我运行py.test时,没有打印任何内容。 这是预期的:默认情况下,py.test捕获输出。

当我运行py.test -s时,它会打印test_a和test_b。

当我运行py.test -s -n2时,再没有打印任何内容。 如何在使用-n2时使print语句正常工作?

我已经阅读了pytest + xdist而没有捕获输出和这个错误报告。


我只是在github上看到关于这个问题的解释https://github.com/pytest-dev/pytest/issues/1693

pytest-xdist使用sys stdin / stdout来控制执行,
显示打印输出的唯一方法应该是std.err。

1
2
3
4
5
6
7
import sys
def test_a():
    print >> sys.stderr, 'test_a'


def test_b():
    print >> sys.stderr, 'test_b'

不是一个好主意,但工作。

另外,您应该注意,如果您使用xdist插件,则arg -s无效。

在python 3中,我认为logging.warning是一个更好的选择,因为它默认设置为写入stderr。

1
2
3
4
5
6
7
8
9
import logging
logging.basicConfig(format='%(message)s')

def test_a():
    logging.warning('test_a')


def test_b():
    logging.warning('test_b')