Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't sys.excepthook work?

Tags:

python

sys

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!

[SOLUTION] if someone has my same problem => Try to Run your code by command line! and not from IDE.

like image 699
NerdEngine Avatar asked Aug 25 '14 22:08

NerdEngine


1 Answers

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()
like image 167
unutbu Avatar answered Sep 21 '22 10:09

unutbu