python - How to get the value in the stack when exception occurs
習慣沉默
習慣沉默 2017-05-18 10:59:04
0
4
661

Suppose there is such a piece of code:

try:
    a = 1
    b = 0
    c = a / b
except Exception as e:
    print(e)

Now I want to get the value of each variable before the exception occurs when the exception occurs, that is, get the result like a=1, b=0.

習慣沉默
習慣沉默

reply all(4)
習慣沉默

inspect.currentframe

>>> import inspect
>>> a=1;b=0;a/b
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    a=1;b=0;a/b
ZeropisionError: pision by zero
>>> f=inspect.currentframe()
>>> f.f_globals['a']
1
>>> f.f_globals['b']
0
>>> 
Ty80

This python should not be able to actively implement it, because if there is such a method, an exception occurs during multi-layer calls, and the corresponding data is recorded layer by layer and then returned, then this is likely to cause memory problems; And before an exception occurs, the virtual machine doesn't know that you have a problem. It's like your division-by-zero exception above is running a/b => 1/0, implemented in the i_pmod function code of PyIntobject , it is judged that the divisor is 0, an exception is triggered directly, and then the stack returns layer by layer to tell the user that an exception has occurred. There is no code related to the value of the symbol recorded in the try_block, so at most people make more detailed code in except. , humanized output

黄舟

Use ipython to open pdb, and you can report which line has an error!

ZeropisionError: integer pision or modulo by zero
> <ipython-input-4-a5ac4c0f15ad>(4)<module>()
      1 
      2 a = 1
      3 b = 0
----> 4 c = a / b

ipdb> 
为情所困

pdb

Add the following code:

#!/usr/bin/env python
# encoding: utf-8

try:
    a = 1
    b = 0
    c = a / b
except Exception as e:
    import pdb; pdb.set_trace()  # <-- 加入断点
    print(e)

Execute as follows:

❯ python sf.py
> /Users/caimaoy/tmp/sf.py(10)<module>()
-> print(e)
(Pdb) ll
  1     #!/usr/bin/env python
  2     # encoding: utf-8
  3
  4     try:
  5         a = 1
  6         b = 0
  7         c = a / b
  8     except Exception as e:
  9         import pdb; pdb.set_trace()
 10  ->     print(e)
(Pdb) p a
1
(Pdb) p b
0
(Pdb)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!