2

在我的一个函数中,我正在调用一个外部程序, using subprocess.check_call,它将产生输出。我如何使用 doctest 来确保它产生的输出是我期望的输出?

4

1 回答 1

2

也许这可以帮助:

import sys
import tempfile
import subprocess


def example(output):
    r""" Do something ...

    >>> output = example('Processing file ...')
    >>> print output # doctest:+ELLIPSIS
    'Processing file ...'

    Check how many file was processed.
    >>> [line.startswith('Processing file')
    ... for line in output.splitlines()].count(True)
    1    

    """
    cmd = "print '%s'" % (output, )
    with tempfile.TemporaryFile() as output:
        subprocess.check_call([sys.executable, '-c', cmd], stdout=output)
        output.seek(0)
        res = output.read()

    return res

if __name__ == '__main__':
    import doctest
    doctest.testmod()

如您所见,我使用了stdout函数的参数subprocess.check_call以便能够获得命令的输出,此外,如果您不使用stdout参数(我认为这是您的情况),我认为很难捕获命令输出。

希望这是有希望的:)

于 2011-06-10T09:58:49.067 回答