如何将python警告重定向到自定义流? [英] How to redirect python warnings to a custom stream?

查看:373
本文介绍了如何将python警告重定向到自定义流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?

推荐答案

尝试重新分配 warnings.showwarning 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")

会将所有警告重定向到stdout。

will redirect all warnings to stdout.

这篇关于如何将python警告重定向到自定义流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆