@direprobs在评论中提供了对这个问题最简单的答案。在调用warn()
后添加这行代码。
sys.stderr.flush()
可以将此代码复制并粘贴到Python 2.7(Jupyter笔记本)中快速运行并查看效果:
实验一(与下面的代码进行比较):
from warnings import warn
from warnings import resetwarnings
class myClass(object):
def __init__(self, numberArg):
if numberArg > 1000:
self._tmpTxt = "That's a really big number for this code." + \
"Code may take a while to run..."
warn("\n%s %s" %(numberArg, self._tmpTxt), stacklevel=1, category=RuntimeWarning)
resetwarnings()
print("If this were real code:")
print("Actions code takes because this is a big number would happen here.")
print("If this were real code, it would be doing more stuff here ...")
mc1 = myClass(1001)
实验二:
from warnings import warn
from warnings import resetwarnings
import sys
class myClass(object):
def __init__(self, numberArg):
if numberArg > 1000:
self._tmpTxt = "That's a really big number for this code." + \
"Code may take a while to run..."
warn("\n%s %s" %(numberArg, self._tmpTxt), category=Warning)
sys.stderr.flush()
print("If this were real code:")
print("Actions code takes because this is a big number would happen here.")
print("If this were real code, it would be doing more stuff here ...")
mc1 = myClass(1001)
实验三:
from warnings import warn
from warnings import resetwarnings
from warnings import filterwarnings
class myClass(object):
def __init__(self, numberArg):
for i in [1,2]:
if numberArg > 1000:
print("loop count %d:" %(i))
self._tmpTxt = "That's a really big number for this code." + \
"Code may take a while to run..."
filterwarnings("once")
warn("\n%s %s" %(numberArg, self._tmpTxt), stacklevel=1, category=RuntimeWarning)
sys.stderr.flush()
print("If this were real code:")
print("Actions code takes because this is a big number would happen here.")
if numberArg > 20000:
self._tmpTxt = "That's a really really really big number for this code." + \
"Code may take a while to run..."
filterwarnings("once", "\nFW: %s %s" %(numberArg, self._tmpTxt))
warn("\n%s %s" %(numberArg, self._tmpTxt), stacklevel=0)
sys.stderr.flush()
print("loop count %d:" %(i))
print("If this were real code, it would be doing more stuff here ...")
mc1 = myClass(1001)
print("====================")
mc2 = myClass(20001)
稍后在github上寻找这段代码。我在此发布它是为了帮助其他人调查如何使用warnings
。
warn
下面加上这个调用:sys.stderr.flush()
. 如果你查看warnings
模块文档,你会发现: "决定是否发布警告消息的是警告过滤器,它是一系列匹配规则和操作。" 可能是一个过滤器问题。先尝试刷新stderr
看看会发生什么。 - GIZ