如何将python警告重定向到自定义流?
假设我有一个类似文件的对象,比如StreamIO,并希望python的警告模块将所有警告消息写入其中。我该怎么做?尝试重新分配,即如何将python警告重定向到自定义流?,python,warnings,io,Python,Warnings,Io,假设我有一个类似文件的对象,比如StreamIO,并希望python的警告模块将所有警告消息写入其中。我该怎么做?尝试重新分配,即 将所有警告重定向到stdout。我认为类似的方法会起作用,尽管它是未经测试的代码,而且界面看起来有一种更干净的方法,目前我还没有找到: import warnings # defaults to the 'myStringIO' file def my_warning_wrapper(message, category, filename, lineno, fil
将所有警告重定向到stdout。我认为类似的方法会起作用,尽管它是未经测试的代码,而且界面看起来有一种更干净的方法,目前我还没有找到:
import warnings
# defaults to the 'myStringIO' file
def my_warning_wrapper(message, category, filename, lineno, file=myStringIO, line=None):
warnings.show_warning(message, category, filename, lineno, file, line)
warnings._show_warning = my_warning_wrapper
如果这还不够的话,查看Lib\warnings.py应该可以帮助您走上正确的道路。请注意-这是与io不同的实现。StringIO StringIO.StringIO没有定义fileno()等方法,而io.StringIO定义了fileno()但没有实现。
import sys
import StringIO
sys.stdout = StringIO.StringIO()
import sys
import StringIO
sys.stdout = StringIO.StringIO()