파이썬에서 예외 값 얻기
그 코드가 있다면 :
try:
some_method()
except Exception, e:
이 예외 값 (문자열 표현)을 어떻게 얻을 수 있습니까?
사용하다 str
try:
some_method()
except Exception as e:
s = str(e)
또한 대부분의 예외 클래스에는 args
속성이 있습니다. 종종 args[0]
오류 메시지가 나타납니다.
str
오류 메시지가 없으면을 사용 하면 빈 문자열이 반환되지만 repr
pyfunc 권장 사항을 사용하면 최소한 예외 클래스가 표시됩니다. 필자는 인쇄하는 경우 클래스가 무엇인지 신경 쓰지 않고 오류 메시지 만 원하는 최종 사용자를위한 것입니다.
실제로 처리하는 예외 클래스와 인스턴스화 방법에 따라 다릅니다. 특별히 염두에 두었습니까?
repr () 사용과 repr과 str 사용의 차이점
사용 repr
:
>>> try:
... print(x)
... except Exception as e:
... print(repr(e))
...
NameError("name 'x' is not defined")
사용 str
:
>>> try:
... print(x)
... except Exception as e:
... print(str(e))
...
name 'x' is not defined
이것이 오래된 질문이라는 것을 알고 있지만 예외 출력을 처리하기 위해 traceback
모듈 을 사용하는 것이 좋습니다 .
traceback.print_exc()
포착되지 않은 채로 인쇄되거나 traceback.format_exc()
문자열과 동일한 출력을 얻는 것과 같이 현재 예외를 표준 오류로 인쇄하는 데 사용하십시오 . 출력을 제한하거나 인쇄를 파일과 같은 객체로 리디렉션하려는 경우 해당 함수 중 하나에 다양한 인수를 전달할 수 있습니다.
다른 방법은 아직 주어지지 않았습니다 :
try:
1/0
except Exception, e:
print e.message
산출:
integer division or modulo by zero
args[0]
실제로 메시지가 아닐 수도 있습니다.
str(e)
따옴표로 묶고 따옴표가 붙은 문자열을 반환 할 수 있습니다 u
.
'integer division or modulo by zero'
repr(e)
아마도 당신이 원하지 않는 완전한 예외 표현을 제공합니다 :
"ZeroDivisionError('integer division or modulo by zero',)"
편집하다
My bad !!! It seems that BaseException.message
has been deprecated from 2.6
, finally, it definitely seems that there is still not a standardized way to display exception messages. So I guess the best is to do deal with e.args
and str(e)
depending on your needs (and possibly e.message
if the lib you are using is relying on that mechanism).
For instance, with pygraphviz
, e.message
is the only way to display correctly the exception, using str(e)
will surround the message with u''
.
But with MySQLdb
, the proper way to retrieve the message is e.args[1]
: e.message
is empty, and str(e)
will display '(ERR_CODE, "ERR_MSG")'
For python2, It's better to use e.message
to get the exception message, this will avoid possible UnicodeDecodeError
. But yes e.message
will be empty for some kind of exceptions like OSError
, in which case we can add a exc_info=True
to our logging function to not miss the error.
For python3, I think it's safe to use str(e)
.
If you don't know the type/origin of the error, you can try:
import sys
try:
doSomethingWrongHere()
except:
print('Error: {}'.format(sys.exc_info()[0]))
But be aware, you'll get pep8 warning:
[W] PEP 8 (E722): do not use bare except
참고URL : https://stackoverflow.com/questions/4308182/getting-the-exception-value-in-python
'Programing' 카테고리의 다른 글
Anaconda를 어떻게 업데이트합니까? (0) | 2020.04.28 |
---|---|
jinja에서 변수 설정 (0) | 2020.04.28 |
Json Serialization에서 속성을 제외하는 방법 (0) | 2020.04.28 |
phpmyadmin에서 기존 테이블에 대한 테이블 생성 스크립트를 생성하는 방법은 무엇입니까? (0) | 2020.04.28 |
foreach와지도 사이에 차이가 있습니까? (0) | 2020.04.28 |