作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我看了几个关于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']
关于python - 运行许多Python线程并获取每个线程的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915890/
我是一名优秀的程序员,十分优秀!