简体   繁体   中英

Why doesn't sys.excepthook work?

Why isn't the sys.excepthook function called if I try to execute this code?

import sys;
def MyExcepthook(ex_cls, ex, tb):

    print("Oops! There's an Error.\n");

    a=open("./ERR.txt","w"); #Fixed as suggested by unutbu BUT the problem is the same!
    a.write("Oops! There's an Error.\n");
    a.close();

sys.excepthook = MyExcepthook;

def main():
    print(1/0);

if (__name__=="__main__"):
    main();

Output:

Traceback (most recent call last):
  File "C:\Users\Path\to\my\python\file.py", line 13, in <module>
    main();
  File "C:\Users\Path\to\my\python\file.py", line 10, in main
    print(1/0);
ZeroDivisionError: division by zero

Expected Output (by print ):

Oops! There's an Error.

and a new file ( Err.txt ) should be created (by open )

The print function doesn't show the text and the file is not created because the sys.excepthook function is not called - why?

-->EDIT My Problem is caused by a bug in idle-python 3.4 because now i tried to run the code by interpreter python (command line) and it works! this makes my Question useless if not to warn about this bug in idle-python 3.4 i'm sorry and thanks for your help!

if someone has my same problem => Try to Run your code by command line! 如果有人有同样的问题=>尝试通过命令行运行您的代码! and not from IDE.

Your custom excepthook must not itself raise an exception:

a=open("./ERR.txt")   # opens the file in read mode

should be

a=open("./ERR.txt", 'w')  # open the file in write mode.

When the custom excepthook raises an exception, you should see something like

Oops! There's an Error.

Error in sys.excepthook:
...
IOError: [Errno 2] No such file or directory: './ERR.txt'

Original exception was:
...
ZeroDivisionError: integer division or modulo by zero

PS. Don't forget to delete all those unnecessary semicolons!

import sys
def my_excepthook(ex_cls, ex, tb):
    msg = "Oops! There's an Error.\n"
    print(msg)

    with open("./ERR.txt", 'w') as a:
        a.write(msg)

sys.excepthook = my_excepthook

def main():
    print(1/0)

if __name__=="__main__":
    main()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM