Python에서 예외를 인쇄하려면 어떻게 해야 합니까?
에러/예외를 인쇄하려면except:블록?
try:
...
except:
print(exception)
Python 2.6 이상 및 Python 3.x의 경우:
except Exception as e: print(e)
Python 2.5 이전의 경우 다음을 사용합니다.
except Exception,e: print str(e)
이 모듈에서는 예외와 그 트레이스 백을 포맷 및 인쇄하는 방법을 제공합니다.예를 들어, 다음과 같이, 디폴트 핸들러와 같이 예외 인쇄를 실시합니다.
import traceback
try:
1/0
except Exception:
traceback.print_exc()
출력:
Traceback (most recent call last):
File "C:\scripts\divide_by_zero.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
Python 2.6 이상에서는 조금 더 깔끔합니다.
except Exception as e: print(e)
이전 버전에서는 여전히 읽을 수 있습니다.
except Exception, e: print e
Python 3:logging
베이직 대신print()기능할수록 모듈을 사용하여 예외를 기록할 수 있습니다.그logging모듈은 메시지 로깅 등 많은 추가 기능을 제공합니다.
- 지정된 로그 파일에 저장하거나
- 타임스탬프 및 로깅 발생 장소에 대한 추가 정보를 제공합니다.
상세한 것에 대하여는, 공문서를 참조해 주세요.
사용.
예외 로깅은 다음과 같이 모듈레벨 함수를 사용하여 실행할 수 있습니다.
import logging
try:
1/0
except BaseException:
logging.exception("An exception was thrown!")
산출량
ERROR:root:An exception was thrown!
Traceback (most recent call last):
File ".../Desktop/test.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
메모들
함수
logging.exception()예외 핸들러에서만 호출해야 합니다.그
logging로깅 핸들러 내에서 모듈을 사용하면RecursionError(PrakharPandey @감사합니다)
대체 로그 수준
키워드 인수를 사용하여 예외를 다른 로그레벨로 기록할 수도 있습니다.exc_info=True다음과 같이 합니다.
logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)
에러 문자열을 건네주는 경우는, 에러와 예외(Python 2.6)의 예를 나타냅니다.
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
(@jldupont의 답변에 코멘트로 남기려고 했는데, 평판이 좋지 않습니다.)
다른 곳에서도 @jldupont의 답변과 같은 답변을 본 적이 있습니다.WWIW, 이 점에 주의해 주십시오.
except Exception as e:
print(e)
에러 출력을 출력합니다.sys.stdout디폴트입니다.일반적으로 오류 처리에 대한 보다 적절한 접근법은 다음과 같습니다.
except Exception as e:
print(e, file=sys.stderr)
(주의:import sys이 기능을 합니다.)이렇게 하면 오류는 다음 주소로 출력됩니다.STDERR대신STDOUT이를 통해 적절한 출력 해석/리다이렉션 등을 수행할 수 있습니다.질문이 '오류 인쇄'에 대한 것이었음을 이해하지만, 결국 더 잘 배우지 못하는 사람에게 비표준적인 코드를 초래할 수 있는 이 세부 사항을 빼놓기 보다는 여기서 모범 사례를 제시하는 것이 중요합니다.
아직 사용하지 않았습니다.tracebackCat Plus의 답변과 같은 모듈입니다.그게 최선일 수도 있지만, 저는 이걸 버리고 싶다고 생각했습니다.
예외를 포착할 때 어떤 트레이스백 정보를 표시/로그할지를 제어할 수 있습니다.
코드
with open("not_existing_file.txt", 'r') as text:
pass
그럼 다음 트레이스백이 생성됩니다.
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
전체 트레이스 백 인쇄/로그
이미 언급한 것처럼 트레이스백모듈을 사용하면 트레이스백 전체를 캡처할 수 있습니다.
import traceback
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
traceback.print_exc()
그러면 다음과 같은 출력이 생성됩니다.
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
로깅을 사용하여 동일한 작업을 수행할 수 있습니다.
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
logger.error(exception, exc_info=True)
출력:
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
File "exception_checks.py", line 27, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
인쇄/로그 오류 이름/메시지만
트레이스백 전체에는 관심이 없지만 예외 이름 및 예외 메시지와 같은 가장 중요한 정보에만 다음을 사용합니다.
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
print("Exception: {}".format(type(exception).__name__))
print("Exception message: {}".format(exception))
출력:
Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
여기서 "Exception as e:" 솔루션을 확장하면 오류 유형 및 발생한 위치 등의 추가 정보가 포함된 라이너 하나가 표시됩니다.
try:
1/0
except Exception as e:
print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")
출력:
ZeroDivisionError at line 48 of /Users/.../script.py: division by zero
#이것을 시험해 보세요
try:
print("Hare Krishna!")
except Exception as er:
print(er)
원하는 경우 assert 문을 사용하여 라이너 오류를 한 번 발생시킬 수 있습니다.이를 통해 정적으로 수정 가능한 코드를 작성하고 오류를 조기에 확인할 수 있습니다.
assert type(A) is type(""), "requires a string"
try-except 스테이트먼트를 사용하는 것을 추천합니다.또한 로깅 예외는 인쇄문을 사용하는 대신 로거에 ERROR 레벨의 메시지를 기록합니다.이러한 메시지는 인쇄 출력보다 효과적입니다.이 메서드는 다음과 같이 예외 핸들러에서만 호출해야 합니다.
import logging
try:
*code goes here*
except BaseException:
logging.exception("*Error goes here*")
로깅 및 디버깅에 대해 자세히 알고 싶다면 이 파이썬 페이지에 좋은 문서가 있습니다.
언급URL : https://stackoverflow.com/questions/1483429/how-do-i-print-an-exception-in-python
'programing' 카테고리의 다른 글
| MySQL 열 정의를 변경하는 방법 (0) | 2022.09.21 |
|---|---|
| "optimize table tablename" 실행 후 테이블 크기가 증가했습니다. (0) | 2022.09.21 |
| strtotime()은 dd/mm/YYY 형식에서 작동하지 않습니다. (0) | 2022.09.21 |
| 사용자가 로그인하고 있는지 확인하는 방법(user.is_interated를 올바르게 사용하는 방법) (0) | 2022.09.21 |
| 다른 경우 트리거(사이) (0) | 2022.09.21 |