2016-11-18 53 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 –