2016-11-18 51 views
0

如何截斷sys.stderr由於異常處理?截斷sys.stderr

import sys 
try: 
    sys.stderr.write('Someone written here') 
    raise Exception 
except: 
    # would like to clean sys.stderr here 
    sys.stderr.write('I only want this') 
    sys.exit(1) 

我想標準誤差僅包含字符串"I only want this"

回答

2

會像這樣幫助你嗎?它只會工作,如果你只打印一條線到stderr到目前爲止:Python - Remove and Replace Printed items

另一種方法來做它只是將stderr附加到一個字符串並打印在一個終端,雖然這不會允許你實時增量打印。

import sys 

stderr_str = '' 
try: 
    stderr_str += 'Someone written here' 
    raise Exception 
except: 
    # would like to clean sys.stderr here 
    stderr_str = '' 
    stderr_str += 'I only want this' 
finally: 
    sys.stderr.write(stderr_str) 

編輯: 您也可以嘗試重新定義標準錯誤到一個類文件對象,如詳細in this answer。即使第三部分模塊寫入標準錯誤,這也應該起作用。

例子:

bash-3.2$ ls 
a.py b.py 
bash-3.2$ cat a.py 
import sys 
import b 

sys.stderr = open('stderr.log', 'a') 
b.raise_exception() 

bash-3.2$ cat b.py 
def raise_exception(): 
    return 1/0 

bash-3.2$ python a.py 
bash-3.2$ ls 
a.py  b.py  b.pyc  stderr.log 
bash-3.2$ cat stderr.log 
Traceback (most recent call last): 
    File "a.py", line 5, in <module> 
    b.raise_exception() 
    File "/Users/username/tmp2/b.py", line 2, in raise_exception 
    return 1/0 
ZeroDivisionError: integer division or modulo by zero 

你基本上可以使用這樣的技術來捕獲所有的標準錯誤,直到結束,然後寫它標準錯誤,或者只是忽略它和你的新的輸出寫入標準錯誤。

+0

stderr正在寫第三方模塊,以及引發的異常。所以這不會是我的選擇 –

+0

添加了一個可能適合你的編輯! –

+0

它的工作,謝謝!以防萬一你想更新你的aswer,在執行'sys.stderr = open('stderr.log','a')''後,我可以調用'sys.stderr.truncate()'。這是不可能使用標準的sys.strerr –