如何将python警告重定向到自定义流?

Paw*_*dan 8 python io warnings

假设我有类似文件的对象,比如StreamIO,并希望python的警告模块向它写入所有警告消息.我怎么做?

cob*_*bal 15

尝试重新分配warnings.show警告 ie

#!/sw/bin/python2.5

import warnings, sys

def customwarn(message, category, filename, lineno, file=None, line=None):
    sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))

warnings.showwarning = customwarn
warnings.warn("test warning")
Run Code Online (Sandbox Code Playgroud)

将所有警告重定向到stdout.