如何在python中找到最后执行的代码行?

时间:2012-10-10 22:59:34

标签: python

有什么最好的工具可以找到在python程序中执行的最后一行代码?谢谢!

2 个答案:

答案 0 :(得分:3)

查看trace模块及其选项。有关更详细的示例,请访问http://www.doughellmann.com/PyMOTW/trace/

答案 1 :(得分:1)

尝试dis模块:

>>> cc=compile("""
def func():print(func1(2))

def func1(x): return x**2

func()
print ("I am last")
"""
,"filename","exec")


>>> eval (cc)
4
I am last

>>> dis.dis(cc)
  2           0 LOAD_CONST               0 (<code object func at 0x9ccf770, file "gf", line 2>) 
              3 MAKE_FUNCTION            0 
              6 STORE_NAME               0 (func) 

  4           9 LOAD_CONST               1 (<code object func1 at 0x9cf63c8, file "gf", line 4>) 
             12 MAKE_FUNCTION            0 
             15 STORE_NAME               1 (func1) 

  6          18 LOAD_NAME                0 (func) 
             21 CALL_FUNCTION            0 
             24 POP_TOP              

  7          25 LOAD_NAME                2 (print) 
             28 LOAD_CONST               2 ('I am last') 
             31 CALL_FUNCTION            1 
             34 POP_TOP              
             35 LOAD_CONST               3 (None) 
             38 RETURN_VALUE