繁体   English   中英

如何测试从 tkinter GUI 中调用的 function 是否产生 RunTimeWarning?

[英]How to test whether a function called from within a tkinter GUI yields a RunTimeWarning?

我对 Python 警告和异常知之甚少,但发现自己处于一种情况,即我正在设计一个 tkinter gui,该 gui 可以选择执行从其他人编写的模块导入的外部 ZC1C425268E68385D1AB5074C17A94F14。 function 执行计算但不生成图表。

Numeric stability issues may arise when I call the function, in which case it returns an output along with a RunTimeWarning that indicates the output may not be very reliable and suggests I adjust the input I used when calling the function.

当然,用户在 gui 中看不到警告,所以我想通知用户警告并为他们提供继续操作的选项。 伪代码如下所示:

输出=outside_function(输入)

if outside_function 发出 RuntimeWarning:做一些事情,比如发出错误信息,要求用户调整输入等。

否则:使用获得的 output 进行进一步计算。

我很抱歉这个问题有些含糊,并且缺少一个最小的可重复示例。 但是有什么方法,也许使用警告模块,它可以让我确定outside_function 发出的 RuntimeWarning是真还是假?

如果警告扩展了WarningRuntimeWarning应该),您应该能够使用catch_warnings上下文管理器捕获它,请参见此处的示例。

但是您应该能够执行以下操作:

import warnings
with warnings.catch_warnings(record=True) as w:
    outside_function(...)
    # code to check if there was a warning
    if len(w) > 0: 
        # do something, e.g. check to see the warning type/whatnot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM