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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.