Python中的线程:如何获取使用target=时的返回值

16 投票
2 回答
46396 浏览
提问于 2025-04-15 21:14

可能是重复的问题:
从线程返回值

我想要获取一堆服务器的“空闲内存”,像这样:

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

因为这个操作可以用线程来处理,所以我想这样做:

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

但是现在:我该如何获取 get_mem 函数的返回值呢?我真的需要创建一个完整的 class MemThread(threading.Thread) 类,并重写 __init____run__ 吗?

2 个回答

2

为了记录一下,这是我最后想到的解决方案(与多进程示例有所不同)

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
21

你可以创建一个同步的队列,然后把这个队列传给线程的函数,让它通过把结果放入队列来反馈信息,比如:

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()

撰写回答