VSCode中Jupyter Notebook使用line_profiler无法显示函数内容的问题
VSCode中Jupyter Notebook使用line_profiler无法显示函数内容的问题
我之前在VSCode的Jupyter Notebook里用line_profiler的时候,也碰到过一模一样的坑!当时是用conda装的4.1.3版本,不管对哪个函数做行分析,都会弹出找不到临时文件的警告,而且输出里完全看不到函数的代码内容,只能看到行号、执行时间这些空架子。
问题还原
当我依次运行这些Notebook单元格时:
%load_ext line_profiler
def test_fn(): x = 2+2 return x
lprun -f test_fn test_fn()
得到的输出是这样的:
Timer unit: 1e-07 s Total time: 3.8e-06 s Could not find file C:\Users\ <user>\AppData\Local\Temp\ipykernel_9076\3402019769.py Are you sure you are running this program from the same directory that you ran the profiler from? Continuing without the function's contents. Line # Hits Time Per Hit % Time Line Contents ============================================================== 1 2 1 18.0 18.0 47.4 3 1 20.0 20.0 52.6
不管换哪个函数测试,结果都是一样的——看不到函数的具体代码,只有时间统计数据。
问题原因
这其实是因为Jupyter Notebook会把每个单元格的代码临时存在系统Temp目录下的ipykernel_xxx文件夹里,而line_profiler没办法正确读取这些临时文件里的函数源代码,所以只能跳过代码内容,只输出统计数据。
可行的解决办法
后来我摸索出一个有效的 workaround,就是把要分析的函数先写到本地的Python文件里,再导入使用:
- 先加载line_profiler扩展:
%load_ext line_profiler
- 用
%%writefile魔法命令把函数写入本地文件(比如test.py):
%%writefile test.py def test_fn(): x = 2+2 return x
- 导入函数后再执行行分析:
from test import test_fn lprun -f test_fn test_fn()
这样就能正常看到包含函数代码的完整分析结果了!
备注:内容来源于stack exchange,提问作者alessandro
相关产品推荐
相关产品推荐

