source

Python에서 검출된 예외의 이름을 얻는 방법은 무엇입니까?

nicesource 2022. 11. 4. 21:26
반응형

Python에서 검출된 예외의 이름을 얻는 방법은 무엇입니까?

Python에서 발생한 예외의 이름을 얻으려면 어떻게 해야 합니까?

예.,

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__
  3. exception.__class__.__qualname__

예.,

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

완전 수식 클래스명을 필요로 하는 경우(예:sqlalchemy.exc.IntegrityError뿐만 아니라IntegrityErrorMB의 멋진 답변에서 가져온 다음 함수를 사용할 수 있습니다(기호에 맞게 변수 이름을 변경했습니다).

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

를 사용할 수도 있습니다.sys.exc_info().exc_info()type, value, traceback의 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]" % exc_type.__name__

다음과 같은 형식화된 문자열을 사용하여 예외를 인쇄할 수 있습니다.

예를 들어:

try:
    #Code to execute
except Exception as err:
    print(f"{type(err).__name__} was raised: {err}")

이게 먹히긴 하는데, 좀 더 쉽고 직접적인 방법이 있을 것 같은데요?

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

여기 있는 다른 답변은 탐색을 위해 좋지만, 예외의 이름을 포함하여 예외를 기록하는 것이 주요 목표라면 인쇄 대신 logging.exception을 사용하는 것을 고려해 주십시오.

언급URL : https://stackoverflow.com/questions/18176602/how-to-get-the-name-of-an-exception-that-was-caught-in-python

반응형