如何在Python中find线程ID

我有一个multithreading的Python程序和一个实用程序函数writeLog(message),它写出一个时间戳,然后是消息。 不幸的是,生成的日志文件没有提供哪个线程正在生成哪个消息。

我想要writeLog()能够添加一些东西到消息来确定哪个线程调用它。 显然,我可以让线程传递这些信息,但是这将是更多的工作。 有一些线程相当于os.getpid(),我可以使用吗?

threading.get_ident()工作,或threading.current_thread() (或Python的threading.currentThread() <2.6)。

使用日志logging模块,您可以在每个日志条目中自动添加当前的线程标识符。 只需在logging器格式string中使用以下LogRecord映射键之一即可:

%(线程)d:线程ID(如果可用)。

%(threadName)s:线程名称(如果可用)。

并设置你的默认处理程序:

 logging.basicConfig(format="%(threadName)s:%(message)s") 

thread.get_ident()函数在Linux上返回一个长整数。 这不是一个真正的线程ID。

我使用这个方法来真正获得Linux上的线程ID:

 import ctypes libc = ctypes.cdll.LoadLibrary('libc.so.6') # System dependent, see eg /usr/include/x86_64-linux-gnu/asm/unistd_64.h SYS_gettid = 186 def getThreadId(): """Returns OS thread id - Specific to Linux""" return libc.syscall(SYS_gettid) 

我看到了这样的线程ID的例子:

 class myThread(threading.Thread): def __init__(self, threadID, name, counter): self.threadID = threadID ... 

线程模块文档也列出name属性:

 ... A thread has a name. The name can be passed to the constructor, and read or changed through the name attribute. ... Thread.name A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. 

我在Python中创build了多个线程,我打印了线程对象,并使用identvariables打印了这个id。 我看到所有的ID都是一样的

 <Thread(Thread-1, stopped 140500807628544)> <Thread(Thread-2, started 140500807628544)> <Thread(Thread-3, started 140500807628544)>