在IPython和控制台中重定向sys.stderr的不一致

时间:2011-08-19 08:06:52

标签: python console ipython stderr redirect

将sys.stderr重定向到IPython和控制台(Gnome终端)中的文本文件会产生不同的结果。

f=open('std.log','w')
sys.stderr=f
raise Exception,"message goes here"

在IPython中,错误信息将被打印到屏幕上。

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 

隐藏错误消息并将其重定向到文本文件。

关于这里发生了什么的任何建议?

1 个答案:

答案 0 :(得分:2)

问题是写入stderr,但IPython的run命令拦截异常。当程序引发未处理的异常时,IPython会将回溯打印到自己的控制台,另外还有一个警告(警告:执行文件失败)。这是通过安装异常挂钩函数sys.excepthook来完成的。

如果您在测试脚本中明确地写入sys.stderr,它将按预期写入日志文件。

要查看异常挂钩,请在脚本中添加print(sys.excepthook)。直接执行时,它将在{IPOthon}中<built-in function excepthook>,类似于<bound method InteractiveShell.excepthook of <IPython.iplib.InteractiveShell object at 0x022FA3F0>>

相关问题