gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:00:24 24 4
gpt4 key购买 nike

我有一个多线程程序,其中一行会导致警告,我想将其静音。我不想让代码中其他任何地方的警告静音。

我可以按照建议做到这一点 in the docs :

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

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

我意识到我可能可以用一些疯狂的东西来解决这个问题,比如用锁保护这个部分,但是有没有一种好的方法可以使这个线程安全?

最佳答案

您可以使用线程接口(interface)来完成。锁定acquire()方法会在w​​ith block 开始执行时调用, block 退出后会调用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()

关于Python 以线程安全的方式在本地抑制警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56043644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com