为了调试在我的代码中观察到的警告,我试图找到一种方法来以编程方式识别我的代码调用的函数堆栈。
举个例子
def func(x):
return func2(x+4)
def func2(x):
return x*3
func(5)
对于上面的代码我想看到类似的东西
func(5)
- func2(9)
pdb
(和其他调试器)可以做到这一点(已添加评论):
C:\>py -m pdb test.py # debug your script
> c:\test.py(1)<module>()
-> def func(x):
(Pdb) l # list lines around current instruction
1 -> def func(x):
2 return func2(x+4)
3
4 def func2(x):
5 return x*3
6
7 func(5)
[EOF]
(Pdb) b 5 # breakpoint in func2 (line 5)
Breakpoint 1 at c:\users\metolone\test.py:5
(Pdb) r # run to breakpoint
> c:\users\metolone\test.py(5)func2() # in func2()
-> return x*3
(Pdb) x # x (the parameter) was 9
9
(Pdb) where # display call stack
c:\dev\python312\lib\bdb.py(600)run()
-> exec(cmd, globals, locals)
<string>(1)<module>()
c:\users\metolone\test.py(7)<module>()
-> func(5) # func(5) called
c:\users\metolone\test.py(2)func()
-> return func2(x+4) # func2 called (what was x?)
> c:\users\metolone\test.py(5)func2()
-> return x*3 # in func2
(Pdb) x # x == 9
9
(Pdb) up # move up stack frame
> c:\users\metolone\test.py(2)func()
-> return func2(x+4) # now in func()
(Pdb) x # x == 5 when about to call func2()
5