Programing

파이썬과 동등한 e.printStackTrace

lottogame 2020. 5. 12. 07:54
반응형

파이썬과 동등한 e.printStackTrace


나는 print(e)(e가 예외 인 경우) 발생한 예외를 인쇄 한다는 것을 알고 있지만, e.printStackTrace()발생한 행에 대한 예외를 정확하게 추적하고 전체 추적을 인쇄하는 Java와 동등한 파이썬을 찾으려고 노력 했습니다.

누구든지 e.printStackTrace()파이썬 에서 동등한 것을 말해 줄 수 있습니까?


import traceback
traceback.print_exc()

except ...:블록 내 에서이 작업을 수행 하면 현재 예외가 자동으로 사용됩니다. 자세한 내용은 http://docs.python.org/library/traceback.html 을 참조하십시오.


또한 있습니다 logging.exception.

import logging

...

try:
    g()
except Exception as ex:
    logging.exception("Something awful happened!")
    # will print this message followed by traceback

산출:

ERROR 2007-09-18 23:30:19,913 error 1294 Something awful happened!
Traceback (most recent call last):
  File "b.py", line 22, in f
    g()
  File "b.py", line 14, in g
    1/0
ZeroDivisionError: integer division or modulo by zero

( http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-m-better-than-print-statements/ 를 통해 전체 역 추적을 인쇄하는 방법을 통해) 프로그램을 중단 하시겠습니까? )


파이썬과 동등한 e.printStackTrace

자바에서는 다음과 같은 일을한다 ( docs ).

public void printStackTrace()

이 Throwable 및 역 추적을 표준 오류 스트림에 인쇄합니다.

이것은 다음과 같이 사용됩니다 :

try
{ 
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}

Java 에서 표준 오류 스트림은 버퍼되지 않으므로 출력이 즉시 도착합니다.

Python 2의 동일한 의미는 다음과 같습니다.

import traceback
import sys
try: # code that may raise an error
    pass 
except IOError as e: # exception handling
    # in Python 2, stderr is also unbuffered
    print >> sys.stderr, traceback.format_exc()
    # in Python 2, you can also from __future__ import print_function
    print(traceback.format_exc(), file=sys.stderr)
    # or as the top answer here demonstrates, use:
    traceback.print_exc()
    # which also uses stderr.

파이썬 3

파이썬 3에서는 예외 객체에서 직접 역 추적을 얻을 수 있습니다 (스레드 코드에서 더 잘 작동 함). 또한 stderr은 line-buffered 이지만 print 함수는 flush 인수를 얻으므로 즉시 stderr에 인쇄됩니다.

    print(traceback.format_exception(None, # <- type(e) by docs, but ignored 
                                     e, e.__traceback__),
          file=sys.stderr, flush=True)

결론:

따라서 Python 3에서는 기본적으로traceback.print_exc() 사용하지만 출력을 버퍼링하므로 출력을 잃을 수 있습니다. 파이썬 3에서 가능한 한 동등한 의미를 얻으려면 with를 사용하십시오 .sys.stderr printflush=True


Adding to the other great answers, we can use the Python logging library's debug(), info(), warning(), error(), and critical() methods. Quoting from the docs for Python 3.7.4,

There are three keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message.

What this means is, you can use the Python logging library to output a debug(), or other type of message, and the logging library will include the stack trace in its output. With this in mind, we can do the following:

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)

And it will output:

'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'

참고URL : https://stackoverflow.com/questions/9555133/e-printstacktrace-equivalent-in-python

반응형