[英]Why doesn't sys.excepthook work?
Why isn't the sys.excepthook
function called if I try to execute this code? 如果我尝试执行此代码,为什么不调用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();
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
): 预期产出(按print
):
Oops! There's an Error.
and a new file ( Err.txt
) should be created (by open
) 并应创建一个新文件( Err.txt
)( open
)
The print
function doesn't show the text and the file is not created because the sys.excepthook
function is not called - why? print
函数不显示文本,因为未调用sys.excepthook
函数而未创建文件 - 为什么?
-->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! - >编辑我的问题是由idle-python 3.4中的一个错误引起的,因为现在我试图通过解释器python(命令行)运行代码并且它可以工作! 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! 这使我的问题无用,如果不在idle-python 3.4中警告这个错误,我很抱歉,谢谢你的帮助!
[SOLUTION] if someone has my same problem => Try to Run your code by command line! [解决方案]如果有人有同样的问题=>尝试通过命令行运行您的代码! and not from IDE. 而不是来自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 当自定义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. 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.