How to obtain a Thread id in Python? How to obtain a Thread id in Python? python python

How to obtain a Thread id in Python?


Using the logging module you can automatically add the current thread identifier in each log entry.Just use one of these LogRecord mapping keys in your logger format string:

%(thread)d : Thread ID (if available).

%(threadName)s : Thread name (if available).

and set up your default handler with it:

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


The thread.get_ident() function returns a long integer on Linux. It's not really a thread id.

I use this method to really get the thread id on Linux:

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