Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 线程和父线程中的异常捕获_Python - Fatal编程技术网

Python 线程和父线程中的异常捕获

Python 线程和父线程中的异常捕获,python,Python,如何在Python线程中很好地捕获异常 如果您有一个线程化的python应用程序,则sys.excepthook不会捕获子系统中的错误 当子级引发异常时,父级将继续运行,不会出现任何问题,因此调试有点困难 import os import sys import signal import string import threading # capture Exceptions def except_catch(type, value, track, thread): import tra

如何在Python线程中很好地捕获异常

如果您有一个线程化的python应用程序,则sys.excepthook不会捕获子系统中的错误

当子级引发异常时,父级将继续运行,不会出现任何问题,因此调试有点困难

import os
import sys
import signal
import string
import threading


# capture Exceptions
def except_catch(type, value, track, thread):
  import traceback

  rawreport = traceback.format_exception(type, value, track)
  report = "\n" . join(rawreport)

  errorlog = open("errors.log", "a")

  if thread != "":
    errorlog.write("Exception in thread: " + thread + "\n\n")

  errorlog.write(("%s\n" + "-" * 30 + "\n\n") % report)

  errorlog.close()
sys.excepthook = except_catch


# capture KeyboardInterrupt
def interrupt_catch(signal, frame):
  print ""
  os._exit(1)
signal.signal(signal.SIGINT, interrupt_catch)


# all your threaded code here
def whatever_threaded_function():
  try:
    a = 1 / 0

  except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    except_catch(exc_type.__name__, exc_value, exc_traceback, threading.current_thread().name)


threading.Thread(target=whatever_threaded_function).start()