如何以编程方式访问 coverage.py 结果?

How do I access coverage.py results programmatically?

使用 coverage.py 我可以生成如下所示的报告:

Name                      Stmts   Miss  Cover   Missing
-------------------------------------------------------
my_program.py                20      4    80%   33-35, 39
my_other_module.py           56      6    89%   17-23
-------------------------------------------------------
TOTAL                        76     10    87%

如何以编程方式从覆盖率结果数据中访问 87 的值以用作另一个程序的输入?

我假设你已经运行

$ coverage run my_program.py arg1 arg2

并想使用它测量的数据。 Coverage.report() returns 总计为浮点数(您可以取它,也可以根据需要将其四舍五入为整数)。 但是该函数会在屏幕上打印一份报告。为了避免这种情况,我们将打开一个文件对象到空设备以吸收它。

import coverage
import os
cov = coverage.Coverage()
cov.load()

with open(os.devnull, "w") as f:
    total = cov.report(file=f)

print("Total: {0:.0f}".format(total))