如果我在脚本中使用这段代码:
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/