但我并没有在代码中使用警告来警告用户。下面是一个基于我在实际代码中遇到的更复杂场景的简单模型:
from warnings import warn
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))
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)
在我的实际代码中,当我实例化执行__init__(self, numberArg)
的类时,在完成警告之后的所有处理之后,将在最后输出警告。为什么会这样?在
更重要的是,有没有一种方法可以确保先输出警告,然后运行其余代码并交付其输出?在
与这里提供的示例一样,所需的效果是在事件发生之前(而不是之后)警告用户将要发生的事情,并像使用警告格式的警告一样提供输出。在
注意:这个问题是在Windows7环境下的iPython/Jupyter上使用python2.7时遇到的
@direprobs在评论中给出了这个问题最简单的答案。在调用
warn()
之后添加这行代码。在sys.stderr.flush()
注意:尽管它来自
sys
库,但您不需要import
语句,因为warnings
写入stderr
并已导入该库。在可以将此代码复制并粘贴到Python2.7(Jupyter笔记本)中,以快速运行它并查看效果:
实验一(与后面的代码进行比较):
实验二:
^{pr2}$实验三:
稍后在github上查找此代码。发布在这里是为了帮助其他人研究如何使用
warnings
。在相关问题 更多 >
编程相关推荐