2010-04-05 6 views
13

Eventuali duplicati:
Return value from threadThreading in python: recuperare il valore di ritorno quando si utilizza target =

voglio arrivare la "memoria libera" di un gruppo di server in questo modo:

def get_mem(servername): 
    res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername) 
    return res.read().strip() 

poiché questo può essere threadato Voglio fare qualcosa del genere:

import threading 
thread1 = threading.Thread(target=get_mem, args=("server01",)) 
thread1.start() 

Ma ora: come posso accedere ai valori restituiti delle funzioni get_mem? Ho davvero bisogno di fare il vero passo in avanti creando un class MemThread(threading.Thread) e sovrascrivendo __init__ e __run__?

+1

Usa markdown (http://daringfireball.net/projects/markdown/syntax), piuttosto che HTML per formattare il codice:. rientrare le righe di codice con 4 spazi iniziali clic sul punto interrogativo arancione la barra degli strumenti dell'editor di post per maggiori informazioni – outis

+1

wow, grazie! È stato veloce! – hansaplast

risposta

14

Si potrebbe creare un sincronizzato queue, passarlo alla funzione filo e farlo riferire spingendo il risultato in coda, ad esempio:

def get_mem(servername, q): 
    res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername) 
    q.put(res.read().strip()) 

# ... 

import threading, queue 
q = queue.Queue() 
threading.Thread(target=get_mem, args=("server01", q)).start() 
result = q.get() 
1

Per la cronaca, questo è quello che finalmente è venuta con (deviato dalla multiprocessing examples

from multiprocessing import Process, Queue 

def execute_parallel(hostnames, command, max_processes=None): 
    """ 
    run the command parallely on the specified hosts, returns output of the commands as dict 

    >>> execute_parallel(['host01', 'host02'], 'hostname') 
    {'host01': 'host01', 'host02': 'host02'} 
    """ 
    NUMBER_OF_PROCESSES = max_processes if max_processes else len(hostnames) 

    def worker(jobs, results): 
     for hostname, command in iter(jobs.get, 'STOP'): 
      results.put((hostname, execute_host_return_output(hostname, command))) 

    job_queue = Queue() 
    result_queue = Queue() 

    for hostname in hostnames: 
     job_queue.put((hostname, command)) 

    for i in range(NUMBER_OF_PROCESSES): 
     Process(target=worker, args=(job_queue, result_queue)).start() 

    result = {} 
    for i in range(len(hostnames)): 
     result.update([result_queue.get()]) 

    # tell the processes to stop 
    for i in range(NUMBER_OF_PROCESSES): 
     job_queue.put('STOP') 

    return result 
Problemi correlati