9

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

0

1 Answer 1

14

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.