2011-08-19 32 views
1

將sys.stderr重定向到IPython和控制檯(Gnome終端)中的文本文件會得到不同的結果。在IPython和控制檯中重定向sys.stderr的不一致性

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 

錯誤消息被隱藏並重定向到文本文件。

關於這裏發生了什麼的任何建議?

回答

2

問題是不是寫入stderr,但IPython的run命令攔截異常。當程序產生未處理的異常時,IPython會將回溯打印到自己的控制檯,並附加一個警告(警告:執行文件時失敗)。這是通過安裝異常掛鉤功能sys.excepthook完成的。

如果您在測試腳本中明確寫入sys.stderr,它將按預期寫入日誌文件。

要查看異常掛鉤,請將print(sys.excepthook)添加到腳本中。當直接執行時,它將在IPython中爲<built-in function excepthook>,類似於<bound method InteractiveShell.excepthook of <IPython.iplib.InteractiveShell object at 0x022FA3F0>>

相關問題