使用 Python doctest 的多行语句

Multiline statements using Python doctest

是否可以使用 python doctest 处理多行语句?

例如,以下内容在 doctest 中不起作用:

>>> for s in [1,2,3]:
...     for t in [4,5,6]:
...         print(s*t)

我需要从doctest中执行以上三个语句。

编辑:我的回答是错误的;请参阅下面 raacer 的评论。我无法删除它,因为它是公认的答案。

那不是 doctest 的工作方式。它测试一个计算结果为一个值的表达式;它不捕获和测试输出。所以你想要做的是创建一个可以测试的列表,你可以使用列表推导在一行中轻松完成:

>>> [s * t for s in [1, 2, 3] for t in [4, 5, 6]]
[4, 5, 6, 8, 10, 12, 12, 15, 18]

你可能做错了什么。下面是正确的例子。

test.py:

"""
>>> for s in [1,2,3]:
...     for t in [4,5,6]:
...         print s*t
4
5
6
8
10
12
12
15
18
"""

它工作得很好:

$ python -m doctest -v test.py
Trying:
    for s in [1,2,3]:
        for t in [4,5,6]:
            print s*t
Expecting:
    4
    5
    6
    8
    10
    12
    12
    15
    18
ok
1 items had no tests:
    test.print_and_return
1 items passed all tests:
   1 tests in test
1 tests in 2 items.
1 passed and 0 failed.
Test passed.

另请注意,doctest 捕获了 return 值和输出:

def print_and_return():
    """
    >>> print_and_return()
    1
    2
    """
    print(1)
    return 2

Any expected output must immediately follow the final '>>> ' or '... ' line containing the code, and the expected output (if any) extends to the next '>>> ' or all-whitespace line.

https://docs.python.org/2/library/doctest.html#how-it-works