Python以线程安全的方式在本地抑制警告

2024-03-29 09:04:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个多线程程序,其中有一行会导致一个警告,我想让它静音。我不想让代码中其他地方的警告静音。你知道吗

我可以这样做,正如建议的in the docs

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    line_that_causes_warning()

但是文档也说it's not thread-safe,因为它设置了模块级警告过滤器。你知道吗

我意识到我可以用一些疯狂的方法来解决这个问题,比如用锁来保护这个部分,但是有没有一个好的方法来保证这个线程的安全呢?你知道吗


Tags: the方法代码in程序警告docs地方
1条回答
网友
1楼 · 发布于 2024-03-29 09:04:17

你可以用线程接口来实现。当with块开始执行时,将调用Lockacquire()方法,在块退出后,将调用release()方法。你知道吗

import warnings
import threading

lock_for_purpose = threading.RLock()
print(lock_for_purpose)
def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with lock_for_purpose:
    print("lock is done")
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        fxn()

相关问题 更多 >