You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 2.7追踪代码时,如何查看getEffectiveLevel()的完整文件路径?

解决Python 2.7追踪时显示函数完整文件路径的问题

你遇到的问题是trace模块默认输出只显示模块名(比如__init__)而不给出完整文件路径,导致无法快速定位getEffectiveLevel()的来源。下面提供几个实用的解决方案,不需要全局搜索就能直接拿到文件路径:

方法1:自定义sys.settrace追踪函数

自己写一个简单的追踪脚本,利用Python的sys.settrace钩子,在函数执行时打印完整的文件路径。这种方式灵活可控,完全适配Python 2.7:

创建一个名为trace_with_path.py的脚本:

import sys

def trace_calls(frame, event, arg):
    if event != 'call':
        return trace_calls
    # 获取当前函数的完整文件路径
    filename = frame.f_code.co_filename
    func_name = frame.f_code.co_name
    # 过滤掉不需要追踪的路径(和你原来的ignore-dir规则一致)
    ignore_dirs = [sys.path.expanduser('~/lib64'), sys.path.expanduser('~/lib'), '/usr']
    if not any(filename.startswith(d) for d in ignore_dirs):
        print(f"--- filename: {filename}, funcname: {func_name}")
    return trace_calls

sys.settrace(trace_calls)

# 导入并运行你的目标脚本
import bin.myscript

然后运行这个脚本:

python trace_with_path.py

这样输出里会直接显示每个调用函数的完整文件路径,你就能一眼找到getEffectiveLevel()对应的__init__.py具体位置了。

方法2:使用pdb调试器定位

如果只是想快速定位这个函数的来源,用pdb断点调试更直接:

  1. 用命令行启动pdb调试你的脚本:
python -m pdb bin/myscript.py
  1. 在pdb提示符下,给目标函数设置断点(getEffectiveLevel是logging模块Logger类的方法,直接指定完整路径):
b logging.Logger.getEffectiveLevel
  1. 运行脚本触发断点:
c
  1. 当程序停在断点时,输入w(where的缩写)查看栈信息,就能看到该函数所在的完整文件路径:
> /usr/lib/python2.7/logging/__init__.py(1325)getEffectiveLevel()
-> logger = self

方法3:使用外部工具py-spy(允许安装工具时可选)

py-spy是一个非侵入式的Python采样分析工具,支持Python 2.7,能直接显示函数的完整文件路径:

  1. 安装py-spy(可以下载预编译二进制包,无需编译环境):
# 以Linux x86_64为例
wget https://github.com/benfred/py-spy/releases/download/v0.3.14/py-spy-0.3.14-linux-x86_64.tar.gz
tar -xzf py-spy-0.3.14-linux-x86_64.tar.gz
  1. 用py-spy追踪你的脚本:
./py-spy trace -- python bin/myscript.py

输出会清晰展示每个函数调用的完整文件路径、行号和调用栈信息。


内容的提问来源于stack exchange,提问作者guettli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:08:56