How to obtain a Thread id in Python?

Charles Anderson picture Charles Anderson · May 28, 2009 · Viewed 223.9k times · Source

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.

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?

Answer

Nicholas Riley picture Nicholas Riley · May 28, 2009

threading.get_ident() works, or threading.current_thread().ident (or threading.currentThread().ident for Python < 2.6).