Python: 如何获取`threading.local`中的所有项
我有一个 threading.local
对象。在调试的时候,我想查看它里面包含的所有对象,虽然我现在只在其中一个线程上。我该怎么做呢?
1 个回答
4
如果你在使用纯Python版本的 threading.local
(也就是 from _threading_local import local
),那么这是可以做到的:
for t in threading.enumerate():
for item in t.__dict__:
if isinstance(item, tuple): # Each thread's `local` state is kept in a tuple stored in its __dict__
print("Thread's local is %s" % t.__dict__[item])
这里有一个实际运行的例子:
from _threading_local import local
import threading
import time
l = local()
def f():
global l
l.ok = "HMM"
time.sleep(50)
if __name__ == "__main__":
l.ok = 'hi'
t = threading.Thread(target=f)
t.start()
for t in threading.enumerate():
for item in t.__dict__:
if isinstance(item, tuple):
print("Thread's local is %s" % t.__dict__[item])
输出结果:
Thread's local is {'ok': 'hi'}
Thread's local is {'ok': 'HMM'}
这个例子利用了纯Python实现的 local
的一个特点:它把每个线程的 local
状态存储在 Thread
对象的 __dict__
中,并使用一个元组对象作为键:
>>> threading.current_thread().__dict__
{ ..., ('_local__key', 'thread.local.140466266257288'): {'ok': 'hi'}, ...}
如果你使用的是用 C
写的 local
实现(通常情况下,如果你直接使用 from threading import local
,就是这种情况),我就不太确定你能否做到这一点。