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

查看:36
本文介绍了如何将 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

#!/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")

会将所有警告重定向到标准输出.

will redirect all warnings to stdout.

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

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