Domanda

Ho un programma multi-threading Python, e una funzione di utilità, writeLog(message), che scrive un timestamp seguito dal messaggio. Purtroppo, il file di registro risultante dà alcuna indicazione di quale thread sta generando quale messaggio.

Vorrei writeLog() per essere in grado di aggiungere qualcosa al messaggio di identificare quale thread sta chiamando. Ovviamente ho potuto solo fare i fili passano queste informazioni in, ma che sarebbe molto più lavoro. C'è qualche filo equivalente di os.getpid() che potrei usare?

È stato utile?

Soluzione

threading.get_ident() funziona, o threading.current_thread().ident (o threading.currentThread().ident per Python <2,6)

Altri suggerimenti

Uso della registrazione modulo che si può aggiungere automaticamente l'identificatore del thread corrente in ciascuna voce di registro . Basta usare uno di questi LogRecord chiavi di mappatura nella stringa di formato di data logger:

  

% (thread) d:. ID thread (se disponibile)

     

% (ThreadName) s:. nome Discussione (se disponibile)

e impostare il gestore predefinito con esso:

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

La funzione thread.get_ident() restituisce un intero lungo su Linux. Non è proprio un ID.

questo metodo per ottenere davvero solo l'ID su Linux:

import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')

# System dependent, see e.g. /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)

Ho visto esempi di ID di thread come questo:

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

I href="http://docs.python.org/library/threading.html#threading.Thread.name" filettatura del modulo Documenti liste name attribuire pure:

...

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.

È possibile ottenere l'ident del thread corrente in esecuzione. L'ident potrebbe essere riutilizzato per altri thread, se il thread corrente termina.

Quando si crea un esempio di filo, un nome è dato implicita al filo, che è il modello: Thread-numero

Il nome non ha alcun significato e il nome non c'è bisogno di essere unico. L'ident di tutti i thread in esecuzione è unico.

import threading


def worker():
    print(threading.current_thread().name)
    print(threading.get_ident())


threading.Thread(target=worker).start()
threading.Thread(target=worker, name='foo').start()

La threading.current_thread function () restituisce il thread in esecuzione corrente. Questo oggetto contiene tutta l'informazione del filo.

Ho generato più thread in Python, ho stampato gli oggetti thread, e ho stampato l'id utilizzando la variabile ident. Vedo tutti gli ID sono gli stessi:

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

Come per @brucexin avevo bisogno di avere identificatore filo-livello di sistema operativo (che = thread.get_ident()!) E usare qualcosa come di seguito non dipendere da numeri particolari e di essere amd64-only:

---- 8< ---- (xos.pyx)
"""module xos complements standard module os""" 

cdef extern from "<sys/syscall.h>":                                                             
    long syscall(long number, ...)                                                              
    const int SYS_gettid                                                                        

# gettid returns current OS thread identifier.                                                  
def gettid():                                                                                   
    return syscall(SYS_gettid)                                                                  

e

---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos

...

print 'my tid: %d' % xos.gettid()

questo dipende Cython però.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top