Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sys.excepthook on multiprocess

I am trying to set custom sys.excepthook on multiprocess. but it does not work.

In below code, I have expected that to print This is my traceback function: string as a prefix of error message, but it doesn't.

code:

from multiprocessing import Process
import time
import traceback
import logging
import sys

def excepthook(etype, evalue, traceback):
    traceback_strs = traceback.format_exception_only(etype, evalue)
    exception_str = "This is my traceback function:" + "\r\n".join(traceback_strs)
    print("ExceptHook")
    print(exception_str)


def subprocess_main():
    sys.excepthook = excepthook
    time.sleep(3)
    raise Exception("HelloWorld")


if __name__ == "__main__":
    p = Process(target=subprocess_main)
    p.start()
    p.join()

Why it does not work?

OS:Windows10
Python: 3.6.3

like image 882
KiYugadgeter Avatar asked Dec 14 '17 14:12

KiYugadgeter


1 Answers

sys.excepthook is called when there is an uncaught exception, but Process has exception handler routine, which consumed the exception before your hook.

If you still want custom exception handling, you may overriden Process.run method:

class MyProcess(Process):

    def run(self):
        try:
            super().run()
        except Exception:
            excepthook(*sys.exc_info())

ps: argument traceback of your original function excepthook shadowed module object traceback, which will trigger an error if it actually being called.

like image 102
georgexsh Avatar answered Nov 20 '22 18:11

georgexsh