Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - How to get Exception Detail in Python3

I want to get details of Exception in Python3

for example... in foo.py

import sys

try:
  {}.encode('utf8')
except:
  err = sys.exc_info()[0]

  print("itself", err)
  print(".args", err.args)

  print("dir", dir(err.args))
  print("type", type(err.args))

  print("vars", vars(err))

  print("--------k,v in vars---------")
  for k,v in vars(err).items():
    print(k)
    print(v)

and stdout is...

itself   <class 'AttributeError'>
.args    <attribute 'args' of 'BaseException' objects>
dir      ['__class__', '__delattr__', '__delete__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__objclass__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
type     <class 'getset_descriptor'>
vars     {'__init__': <slot wrapper '__init__' of 'AttributeError' objects>, '__doc__': 'Attribute not found.', '__new__': <built-in method __new__ of type object at 0x821c3a0>}
--------k,v in vars---------
__init__
<slot wrapper '__init__' of 'AttributeError' objects>
__doc__
Attribute not found.
__new__
<built-in method __new__ of type object at 0x821c3a0>

I want more information of this built in Exception class from instance "err",

such as

  • FILE : foo.py
  • LINE : 4
  • MESSAGE : 'dict' object has no attribute 'encode'

just like stdout of this code

{}.encode('utf8')

this

Traceback (most recent call last):

  File "foo.py", line 2, in <module>

    {}.encode('utf8')

AttributeError: 'dict' object has no attribute 'encode'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the traceback module to print tracebacks from your current position or for a given exception.

You don't state what output you are expecting, but the traceback module most likely will be able to produce output best suited for your needs, whatever they may be.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...