gpt4 book ai didi

python - 运行许多Python线程并获取每个线程的返回值

转载 作者:行者123 更新时间:2023-12-01 05:12:21 24 4
gpt4 key购买 nike

所以我看了几个关于SO的问题,还有几个网页,以及thread的python页面。 , threading ,和multiprocessing ,但我似乎找不到任何可以满足我要求的东西。

我见过一些使用队列的实现,但它们也不是我真正想要的。

有没有办法我可以做这样的事情:

hosts = "host1 host2 host3 host4 host5".split() #lazy but meh
cpuInfo = {}

threadPool = ThreadPool(processes=len(hosts))

def getCPUUsage(host):
proc = Popen("ssh %s.rest.of.host.name top -bin 1" % host, stdout=PIPE, shell=True)
return proc.stdout.read()

for host in hosts:
cpuInfo[host] = threadPool.newThread(getCPUUsage(host)).getFunctionReturnStuff())

threadPool.waitUntilFinished()

print cpuInfo # Some dictionary with a `top -bin 1` output for each host.

到目前为止,我见过的唯一示例使用队列通过传递 queue 从各个线程中获取所有信息。作为函数的参数,并让函数手动将其 reutnr 值添加到所述队列 - 或者它们根本不返回任何内容,而只是 print - 这对我来说没用。

最佳答案

以下示例为计算机上的每个 CPU 启动一个工作线程。对于列表中的每个主机名,它告诉工作人员通过 ssh 连接到该计算机,运行命令,并将结果返回给原始调用者。就我而言,我只是通过 ssh 连接到我的笔记本电脑,但您明白了。

import multiprocessing, subprocess

def get_value(args):
hostname = args[0]
return subprocess.check_output(
'ssh {} hostname'.format(hostname),
shell=True,
)

pool = multiprocessing.Pool()
print list( pool.imap_unordered(
get_value,
[ ('localhost',) ],
) )

我的笔记本电脑的输出示例:

['palabras\n']

参见:https://docs.python.org/2/library/multiprocessing.html

关于python - 运行许多Python线程并获取每个线程的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com