DRYな備忘録

Don't Repeat Yourself.

Python3でExceptionの詳細を取得したい【Python3.3.2】【try-except】【stackoverflowの回答早すぎワロタな件】

【問題】

Python2系だと、Exceptionのメッセージ取得するのカンタンなのに…

[22:41:10] % python --version
Python 2.7.1
[22:41:13] % python
>>>
>>> try:
...     {}.encode('utf8')
... except Exception as e:
...     print('---- print works ---')
...     print(e.message)
...     print('----------print end-')
...
---- print works ---
'dict' object has no attribute 'encode'
----------print end-
>>>

なのになのに、Python3系だとExceptionがうんこみたいに不親切になっててびびった

[22:43:57] % python --version
Python 3.3.2
[22:44:02] % python
>>>
>>> try:
...     {}.encode('utf8')
... except Exception as e:
...     print('--- print works ---')
...     print(e.message)
...     print('-----print end-----')
...
--- print works ---
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: 'dict' object has no attribute 'encode'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
AttributeError: 'AttributeError' object has no attribute 'message'
>>>

… え … えー…(; ・`д・´)

【解決】

f:id:otiai10:20130725230211p:plain

stackoverflowで聞いたら、そっこー回答ついたwww

tracebackというモジュールがあるらしい

test.py

import traceback,sys

try:
  {}.encode('utf8')
except:
  ex, ms, tb = sys.exc_info()
  print("\nex -> \t",type(ex))
  print(ex)
  print("\nms -> \t",type(ms))
  print(ms)
  print("\ntb -> \t",type(tb))
  print(tb)

  print("\n=== and print_tb ===")
  traceback.print_tb(tb)

そしたら

[22:55:04] % python test.py

ex ->    <class 'type'>
<class 'AttributeError'>

ms ->    <class 'AttributeError'>
'dict' object has no attribute 'encode'

tb ->    <class 'traceback'>
<traceback object at 0xb72c052c>

=== and print_tb ===
  File "main.py", line 4, in <module>
    {}.encode('utf8')

ぱないの…!!

tracebackモジュールは他にも色々メソッドがあるっぽいので調べよう

【雑感】

stackoverflowに質問投げたら1分経たずに回答付いてくそワロタ。今後どんどん使っていきたいでふ


DRY

入門 Python 3

入門 Python 3