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

Python3如何在代码任意位置(运行中途)启动逐行代码追踪功能?

Python3 实现任意位置启动逐行追踪的方法

Python3 原生支持按需启动逐行追踪,不需要从命令行全程开启,以下是两种可直接使用的实现方案:

方案1:基于sys.settrace的轻量自定义实现

这种方式可以灵活过滤不需要追踪的模块(比如标准库、第三方依赖),输出简洁:

import sys, os
import time
import urllib.request

# 先定义追踪函数
def start_trace():
    def trace_func(frame, event, arg):
        # 只追踪当前脚本的代码,过滤标准库/其他模块
        if event == 'line' and frame.f_code.co_filename == __file__:
            print(f"{os.path.basename(frame.f_code.co_filename)}({frame.f_lineno}): {frame.f_code.co_name}")
        return trace_func
    sys.settrace(trace_func)

with urllib.request.urlopen('http://www.example.com/') as f:
    html = f.read().decode('utf-8')

print("A: {}".format(time.time()))

# 在此处启动追踪,前面的代码不会产生追踪输出
start_trace()

time.sleep(2)

print("B: {}".format(time.time()))

直接用普通命令运行python3 test.py,输出效果如下:

A: 1634285044.6374931
test.py(22): <module>
test.py(24): <module>
B: 1634285046.6485002

所有追踪内容只会从start_trace()调用之后开始产生,且只会输出当前脚本的代码行号,不会包含导入、urllib执行的无关追踪信息。如果需要追踪其他自写模块,调整过滤条件判断文件路径是否属于你的项目目录即可。

方案2:基于标准库trace.Trace的实现

如果你需要用到trace模块的原生统计、调用关系等功能,可以直接在代码中实例化Trace对象,不需要从命令行启动:

import sys, os
import time
import urllib.request
from trace import Trace

with urllib.request.urlopen('http://www.example.com/') as f:
    html = f.read().decode('utf-8')

print("A: {}".format(time.time()))

# 启动追踪,ignoredirs参数自动过滤标准库内容
tracer = Trace(trace=True, count=False, ignoredirs=[sys.prefix, sys.exec_prefix])
sys.settrace(tracer.globaltrace)

time.sleep(2)

print("B: {}".format(time.time()))

# 停止追踪
sys.settrace(None)

这个方案会保留trace模块原生的输出格式,输出和你注释掉urllib段后的简洁追踪输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:54:04