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/

相关文章:

python - 基方法和子方法签名中的参数数量不一致

python - Pyplot 散点图,使用facecolors ='none' ,并将边缘颜色保持为默认的确定性标记颜色选择

gcc - 使用 GCC 有选择地删除警告消息

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

angular - 检测到循环依赖项中的警告 - Angular Cli

python - 矩阵中列的最大值列表(没有 Numpy)

python - 返回我的错误是 `Access denied for user ' root' @'localhost'(使用密码 : YES )`. Even when I use ` mike`

Eclipse - @SuppressWarnings ("javadoc")不起作用

c++ - 抑制从类型 'A' 到类型 'B' 的 g++ 警告强制转换消除常量

python - 在 Python 3.5 中使用 find.() 查找重叠子字符串