Python警告总是显示而不是一次

pos*_*ich 5 python warnings deprecated deprecation-warning

我试图用来warnings.simplefilter显示我的警告一次。我已经为DeprecationWarning. 我尝试将它simplefilter放在与我的警告相同的模块中,并在包级别 init 中尽可能地放在顶部,但它始终会在每次调用时显示警告。在 python 3.4 中测试。

我的警告:

class MyDeprecationWarning(DeprecationWarning):
    pass
Run Code Online (Sandbox Code Playgroud)

我如何调用 simplefilter:

warnings.simplefilter('once', MyDeprecationWarning)
Run Code Online (Sandbox Code Playgroud)

我如何调用警告:

warnings.warn("Warning!", MyDeprecationWarning)
Run Code Online (Sandbox Code Playgroud)

有什么问题?

Noc*_*wer 3

如果您的程序多次运行或某些代码在单独的进程中运行,则您可能没有按正确的顺序发出命令。以下程序按预期工作。

import warnings


class MyDeprecationWarning(DeprecationWarning):
    pass


def main():
    print('Program Starting')
    warnings.simplefilter('once', MyDeprecationWarning)
    for _ in range(100):
        warnings.warn('Warning!', MyDeprecationWarning)
    print('Program Finished')


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)