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

Jac*_*ing 4 python coverage.py

使用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%
Run Code Online (Sandbox Code Playgroud)

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

Car*_*ten 5

I will assume that you have already run

$ coverage run my_program.py arg1 arg2
Run Code Online (Sandbox Code Playgroud)

and want to use the data it measured. Coverage.report() returns the total as a floating-point number (you can take it, or round it to a whole percentage if you like). But the function prints a report on the screen. To avoid that, we will open a file object to the null device to suck it up.

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))
Run Code Online (Sandbox Code Playgroud)