如何恢复传递给multiprocessing.Process的函数的返回值?



我已经看了这个问题开始,它工作得很好,我如何才能恢复传递给multiprocessing.Process的函数的返回值?

但我的情况我想写一个小工具,可以连接到很多电脑和收集一些数据,每个属性将聚集过程中干脆点。但是,当我试图将多处理命令封装在机器的类中时,它就失败了。

我的代码

import multiprocessing 
import pprint

def run_task(command):
p = subprocess.Popen(command, stdout = subprocess.PIPE, universal_newlines = True, shell = False)
result = p.communicate()[0]
return result

MACHINE_NAME = "cptr_name"
A_STAT = "some_stats_A"
B_STAT = "some_stats_B"
class MachineStatsGatherer():
def __init__(self, machineName):
self.machineName = machineName
manager = multiprocessing.Manager() 
self.localStats = manager.dict() # creating a shared ressource for the sub processes to use
self.localStats[MACHINE_NAME] = machineName
def gatherStats(self):
self.runInParallel(
self.GatherSomeStatsA,
self.GatherSomeStatsB,
)
self.printStats()
def printStats(self):
pprint.pprint(self.localStats)
def runInParallel(self, *fns):
processes = []
for fn in fns:
process = multiprocessing.Process(target=fn, args=(self.localStats))
processes.append(process)
process.start()
for process in processes:
process.join()
def GatherSomeStatsA(self, returnStats):
# do some remote command, simplified here for the sake of debugging
result = "Windows"
returnStats[A_STAT] = result.find("Windows") != -1

def GatherSomeStatsB(self, returnStats):
# do some remote command, simplified here for the sake of debugging
result = "Windows"
returnStats[B_STAT] = result.find("Windows") != -1

def main():
machine = MachineStatsGatherer("SOMEMACHINENAME")
machine.gatherStats()
return
if __name__ == '__main__':
main()

这里是错误信息

Traceback (most recent call last):
File "C:UsersmesirardAppDataLocalProgramsPythonPython37libmultiprocessingprocess.py", line 297, in _bootstrap
self.run()
File "C:UsersmesirardAppDataLocalProgramsPythonPython37libmultiprocessingprocess.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "d:workdirtrunks6ToolsVTKAppTesterUtilsNXMachineMonitorShared.py", line 45, in GatherSomeStatsA
returnStats[A_STAT] = result.find("Windows") != -1
TypeError: 'str' object does not support item assignment
Process Process-3:
Traceback (most recent call last):
File "C:UsersmesirardAppDataLocalProgramsPythonPython37libmultiprocessingprocess.py", line 297, in _bootstrap
self.run()
File "C:UsersmesirardAppDataLocalProgramsPythonPython37libmultiprocessingprocess.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "d:workdirtrunks6ToolsVTKAppTesterUtilsNXMachineMonitorShared.py", line 50, in GatherSomeStatsB
returnStats[B_STAT] = result.find("Windows") != -1
TypeError: 'str' object does not support item assignment

问题来自这一行

process = multiprocessing.Process(target=fn, args=(self.localStats))

应该有一个额外的逗号在参数的末尾,像这样

process = multiprocessing.Process(target=fn, args=(self.localStats,))

最新更新