반응형
파이썬에서 잡힌 예외의 이름을 얻는 방법?
파이썬에서 발생한 예외의 이름을 어떻게 얻을 수 있습니까?
예 :
try:
foo = bar
except Exception as exception:
name_of_exception = ???
assert name_of_exception == 'NameError'
print "Failed with exception [%s]" % name_of_exception
예를 들어, 여러 (또는 모든) 예외를 포착하고 있으며 오류 메시지에 예외 이름을 인쇄하려고합니다.
다음은 예외 이름을 가져 오는 두 가지 방법입니다.
type(exception).__name__
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
반응형
'developer tip' 카테고리의 다른 글
Error : (9, 5) error : resource android : attr / dialogCornerRadius not found (0) | 2020.08.20 |
---|---|
자바에서 Python을 호출 하시나요? (0) | 2020.08.19 |
lsof 생존 가이드 (0) | 2020.08.19 |
사전 이해에서 if / else를 사용하는 방법? (0) | 2020.08.19 |
(i == -i && i! = 0)에 대한 i 값은 Java에서 true를 반환합니다. (0) | 2020.08.19 |