如果我尝试执行此代码,为什么不调用sys.excepthook函数?

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();

输出:
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

预期输出(按print):
Oops! There's an Error.

并且应该创建一个新文件(Err.txt)(通过open)
print函数不显示文本并且未创建文件,因为未调用sys.excepthook函数-为什么?

->编辑
我的问题是由idle-python 3.4中的一个错误引起的,因为现在我尝试通过解释器python(命令行)运行代码,并且可以正常工作!如果不对idle-python 3.4中的此错误进行警告,这将使我的问题无济于事,非常抱歉,感谢您的帮助!

[解决方案]如果有人遇到我同样的问题=>尝试通过命令行运行您的代码!而不是来自IDE。

最佳答案

您的自定义excepthook本身不能引发异常:

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

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

当自定义excepthook引发异常时,您应该看到
就像是
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。不要忘记删除所有不必要的分号!
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()

关于python - sys.excepthook为什么不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25495028/

10-09 18:33