python-3.x - 警告模块两次打印部分警告

标签 python-3.x warnings

如果我在脚本中使用这段代码:

import warnings
if True:
    warnings.warn(
        "The specified directory is not empty, and does not "
        "appear to contain a pipeline we can update. Exiting."
    )

我得到这个作为输出:

~ > create.py -p something -o .
somethings.py:58: UserWarning: The specified directory is not empty, and does not appear to contain a pipeline we can update. Exiting.
  "The specified directory is not empty, and does not"
~ >

为什么 The specified directory is not empty, and does not string printed again 我该如何关闭它?

最好的问候。

最佳答案

试试这个:

warnings.warn("The specified directory is not empty, and does not "
              "appear to contain a pipeline we can update. Exiting.", stacklevel=2)

这会给你以下警告:

sys:1: UserWarning: The specified directory is not empty, and does not appear to contain a pipeline we can update. Exiting.

警告默认为堆栈级别 1,这就是它被重复的原因。第一层堆栈告诉用户警告源自的确切代码行,这是您的警告函数调用行。所以通过将它放在堆栈级别 2,它不会显示警告行,而只会显示警告本身。

如果您有兴趣更多地自定义警告输出,可以使用 warnings.warn_explicit() 函数。

https://docs.python.org/3.6/library/warnings.html#available-functions

关于python-3.x - 警告模块两次打印部分警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60083173/

相关文章:

Javac/Eclipse - 如果方法没有抛出它可能抛出的最具体的异常,则会发出警告

c - C中的String Inverter Program中的警告

android - 解释 ClickableViewAccessibility

python: `int`和 `float`的组合

python - 如何使用QPropertyAnimation配合QPainter绘制圆弧

python - 构建函数 saving_calculator(PMT, n, i )` that calculates your customer' s 退休时的储蓄

python - Python 中的基本 bool 表达式产生令人惊讶的结果

php - 仅对部分代码禁用 PHP 警告

xcode - 如何在新的 xCode 中禁用 "Add explicit braces to avoid dangling else"?

python - weakref.proxy 和 weakref.ref 之间的区别?