Python doctest 结果死活写不到文件里面去怎么办?

系统:Ubuntu
python:2.7.6
我看别人都能写到文件里面, 我只能输出到终端中,难道我的打开方式有问题
这个是我看的官方实例,也不行


def factorial(n):
    """Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.

>>> # comments are ignored >>> # comments are ignored >>> x = 12 >>> x

>>> if x == 13:
...     print "yes"
... else:
...     print "no"
...     print "NO"
...     print "NO!!!"
...


"""

import math
if not n >= 0:
    raise ValueError("n must be >= 0")
if math.floor(n) != n:
    raise ValueError("n must be exact integer")
if n+1 == n:  # catch a value like 1e300
    raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
    result *= factor
    factor += 1
return result

if name == “main”: import doctest doctest.testmod()


Python doctest 结果死活写不到文件里面去怎么办?

5 回复

我这边试了一下也是不行啊,会不会是搞错了?

我看文档里面的例子的第二部分是执行文件里的测试用例而不是输出结果到文件里,两个部分都试验了一下结果都是输出在终端的


我遇到这个问题时也折腾了半天。doctest默认是输出到stdout的,你得用doctest.testfile()或者doctest.testmod()optionflags参数配合sys.stdout重定向。

最简单的解决方案:

import doctest
import sys

# 把标准输出重定向到文件
with open('doctest_results.txt', 'w') as f:
    sys.stdout = f
    doctest.testmod(your_module)  # 或者 testfile('your_file.py')
    sys.stdout = sys.__stdout__  # 记得恢复

更推荐的做法是用doctest.run_docstring_examples配合自定义输出:

import doctest
import io

def run_doctests_to_file(module, filename='doctest_output.txt'):
    finder = doctest.DocTestFinder()
    runner = doctest.DocTestRunner(verbose=True)
    
    with open(filename, 'w') as f:
        for test in finder.find(module):
            output = io.StringIO()
            runner.run(test, out=output.write)
            f.write(output.getvalue())

# 使用
import your_module
run_doctests_to_file(your_module)

关键点:doctest默认设计就是给交互式用的,要输出到文件就得自己接管输出流。

总结:重定向stdout或者用StringIO捕获输出。

文档我有看,你要不试试在命令行加上“> test.log ” 把标准输出定向到文件?

我关键是想把结果输出到代码里面,方便输出文档

回到顶部