Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将python警告重定向到自定义流?_Python_Warnings_Io - Fatal编程技术网

如何将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

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

尝试重新分配,即


将所有警告重定向到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()