进程如何在Python中彼此共享列表? [英] How can processes share list between each other in Python?
问题描述
请如此指出我如何在进程之间共享列表或数组,以便他们可以访问/追加/删除其中的数据?我需要使用Manager吗? 例如,我有使用多处理程序对多个主机执行ping操作的代码:
Please be so kind to point me on how can a list or an array be shared between processes so they can access/append/delete data from it? Do i need to use Manager for it? For example i have code that pings several hosts using multiprocessing:
#!/usr/bin/env python
from multiprocessing import Pool
import os
def ping(ip):
report = ("No response","Partial Response","Alive")
pingaling = os.popen("ping -q -c2 "+str(ip),"r")
while 1:
line = pingaling.readline()
try:
result = line[line.find(','):].split()[1]
output = report[int(result[0])]
except:
pass
if not line: break
print "Testing %s : %s!" % (ip, output)
if __name__ == '__main__':
pool = Pool(processes=3)
host = ['81.24.212.'+str(x) for x in range(10)]
pool.map(ping, host, 1)
pool.close()
pool.join()
但是输出未排序,但是我想将输出添加到数组并对其进行排序:
But the output is unsorted, however i want to add output to an array and sort it:
Testing 81.24.212.1 : Alive!
Testing 81.24.212.2 : Alive!
Testing 81.24.212.6 : Alive!
Testing 81.24.212.0 : No response!
Testing 81.24.212.5 : No response!
Testing 81.24.212.3 : No response!
Testing 81.24.212.4 : No response!
Testing 81.24.212.9 : No response!
Testing 81.24.212.7 : No response!
Testing 81.24.212.8 : No response!
推荐答案
请注意,pool.map
的行为与buildin map
函数非常相似,并且它返回给定元素的给定函数应用结果的列表.在给定的列表中.
note that pool.map
acts a lot like the buildin map
function and like it returns a list of the results of the application of the given function to elements in the given list.
因此您只需要让ping()
返回找到的内容然后执行:
so you need only have ping()
return what it found and then do:
list_of_values = pool.map(ping, host, 1)
之后,您可以随意使用list_of_values
after which you can use the list_of_values
any way you like
这篇关于进程如何在Python中彼此共享列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!