如何在 Python 中获取线程 ID? [英] How to obtain a Thread id in Python?
问题描述
我有一个多线程 Python 程序和一个实用函数,writeLog(message)
,它写出一个时间戳,然后是消息.不幸的是,生成的日志文件没有给出哪个线程正在生成哪个消息的指示.
I have a multi-threading Python program, and a utility function, writeLog(message)
, that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message.
我希望 writeLog()
能够在消息中添加一些内容以识别哪个线程正在调用它.显然,我可以让线程传递这些信息,但这需要做更多的工作.是否有一些我可以使用的与 os.getpid()
等效的线程?
I would like writeLog()
to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid()
that I could use?
推荐答案
threading.get_ident()
有效,或 threading.current_thread().ident
(或 threading.currentThread().ident
对于 Python <2.6).
threading.get_ident()
works, or threading.current_thread().ident
(or threading.currentThread().ident
for Python < 2.6).
这篇关于如何在 Python 中获取线程 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!