追踪Python:仅包括部分文件

25 投票
4 回答
6713 浏览
提问于 2025-04-19 19:53

我知道我可以用这个来跟踪命令的执行:

python -m trace -t script.py

但是我想减少输出内容:只想显示在我的 src/ 文件夹里的文件(通过 pip install -e ... 安装的)。

我该怎么做呢?

4 个回答

3

我想减少输出内容

这里没有白名单过滤,但有黑名单:

ignore_module:

--ignore-module= 忽略给定的模块名称及其子模块(如果它是一个包)。这个参数可以是用逗号分隔的名称列表。

4

根据文档的说明,你可以通过编程的方式使用trace

import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# run the new command using the given tracer
tracer.run('main()')

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")

注意trace.Trace中的ignoredirs参数。

虽然似乎没有办法明确只包含src中的文件,但你可以排除所有系统包,这在实际操作中应该是一样的。

24

如果你是在 bash 里运行脚本,可以用下面的方式:

python -m trace --ignore-dir=$(python -c 'import sys ; print ":".join(sys.path)[1:]') -t ./script.py

对于 python3 来说:

python -m trace --ignore-dir=$(python -c 'import sys ; print(":".join(sys.path)[1:])') -t ./script.py

这样做的话,你就不用担心自己是否在一个虚拟环境里,或者其他更复杂的情况了。

13

我的解决方案是基于Brian Cain的回答:

export PYTHONIOENCODING=utf-8
python -m trace --ignore-dir=$HOME/lib64:$HOME/lib:/usr -t script.py

我的虚拟环境直接放在$HOME目录下,而我的代码是以可编辑的方式安装在$HOME/src目录里。

这里需要设置 PYTHONIOENCODING=utf-8;,因为如果我的Python代码中有非ASCII字符,就会出现Unicode错误。

撰写回答