重定向系统。在IPython和控制台(Gnome终端)中对文本文件执行stderr会产生不同的结果。
f=open('std.log','w')
sys.stderr=f
raise Exception,"message goes here"
在ippython中,错误信息直接打印到屏幕上。
In [13]: run std.py
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
/home/xiaohan/code/diving-in-python/htmlparser/std.py in <module>()
2 f=open('std.log','w')
3 sys.stderr=f
----> 4 raise Exception,"message goes here"
5
6
Exception: message goes here
WARNING: Failure executing file: <std.py>
但是,如果我直接在控制台中运行它。
python std.py
错误信息被隐藏并重定向到文本文件。
有什么建议吗?
问题是不是写入stderr
,而是IPython的run
命令拦截异常。当程序引发一个未处理的异常时,IPython将把回溯信息打印到自己的控制台中,并加上一个额外的警告( warning: Failure execution file)。这是通过安装异常钩子函数sys.excepthook
来完成的。
如果您在测试脚本中显式地写入sys.stderr
,那么它将按照预期被写入日志文件。
要查看异常钩子,将print(sys.excepthook)
添加到脚本中。当直接执行时,它将是<built-in function excepthook>
,在ippython中,类似于<bound method InteractiveShell.excepthook of <IPython.iplib.InteractiveShell object at 0x022FA3F0>>
。