developer tip

파이썬에서 잡힌 예외의 이름을 얻는 방법?

optionbox 2020. 8. 19. 07:59
반응형

파이썬에서 잡힌 예외의 이름을 얻는 방법?


파이썬에서 발생한 예외의 이름을 어떻게 얻을 수 있습니까?

예 :

try:
    foo = bar
except Exception as exception:
    name_of_exception = ???
    assert name_of_exception == 'NameError'
    print "Failed with exception [%s]" % name_of_exception

예를 들어, 여러 (또는 모든) 예외를 포착하고 있으며 오류 메시지에 예외 이름을 인쇄하려고합니다.


다음은 예외 이름을 가져 오는 두 가지 방법입니다.

  1. type(exception).__name__
  2. exception.__class__.__name__

예 :

try:
    foo = bar
except Exception as exception:
    assert type(exception).__name__ == 'NameError'
    assert exception.__class__.__name__ == 'NameError'

이것은 효과가 있지만 더 쉽고 직접적인 방법이 있어야 할 것 같습니다.

try:
    foo = bar
except Exception as exception:
    assert repr(exception) == '''NameError("name 'bar' is not defined",)'''
    name = repr(exception).split('(')[0]
    assert name == 'NameError'

를 사용할 수도 있습니다 sys.exc_info(). exc_info()유형, 값, 역 추적의 3 가지 값을 반환합니다. 문서 : https://docs.python.org/3/library/sys.html#sys.exc_info

import sys

try:
    foo = bar
except Exception:
    exc_type, value, traceback = sys.exc_info()
    assert exc_type.__name__ == 'NameError'
    print "Failed with exception [%s]" % name_of_exception

정규화 된 클래스 이름 (예 : sqlalchemy.exc.IntegrityError대신 IntegrityError) 을 원하면 아래 함수를 사용할 수 있습니다. MB의 멋진 답변 에서 다른 질문에 대한 답변가져 왔습니다 (내 취향에 맞게 일부 변수 이름을 변경했습니다).

def get_full_class_name(obj):
    module = obj.__class__.__module__
    if module is None or module == str.__class__.__module__:
        return obj.__class__.__name__
    return module + '.' + obj.__class__.__name__

예:

try:
    # <do something with sqlalchemy that angers the database>
except sqlalchemy.exc.SQLAlchemyError as e:
    print(get_full_class_name(e))

# sqlalchemy.exc.IntegrityError

참고 URL : https://stackoverflow.com/questions/18176602/how-to-get-name-of-exception-that-was-caught-in-python

반응형