警告模块两次打印部分警告

Warnings module prints part of warning twice

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

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 字符串,如何关闭它?

此致。

试试这个:

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