如何使用类实例进行多处理

时间:2014-07-08 10:27:41

标签: python class wmi instance pickle

该程序旨在在网络上的各种ips上设置进程创建侦听器。代码是:

import multiprocessing
from wmi import WMI

dynaIP = ['192.168.165.1','192.168.165.2','192.168.165.3','192.168.165.4',]

class WindowsMachine:
    def __init__(self, ip):
        self.ip = ip

        self.connection = WMI(self.ip)
        self.created_process = multiprocessing.Process(target = self.monitor_created_process, args = (self.connection,))
        self.created_process.start()

    def monitor_created_process(self, remote_pc):
        while True:
            created_process = remote_pc.Win32_Process.watch_for("creation")
            print('Creation:',created_process.Caption, created_process.ProcessId, created_process.CreationDate)
            return created_process

if __name__ == '__main__':
    for ip in dynaIP:
        print('Running', ip)

        WindowsMachine(ip)

运行代码时出现以下错误:

Traceback (most recent call last):
  File "U:/rmarshall/Work For Staff/ROB/_Python/__Python Projects Code/multipro_instance_stack_question.py", line 26, in <module>
    WindowsMachine(ip)
  File "U:/rmarshall/Work For Staff/ROB/_Python/__Python Projects Code/multipro_instance_stack_question.py", line 14, in __init__
    self.created_process.start()
  File "C:\Python33\lib\multiprocessing\process.py", line 111, in start
    self._popen = Popen(self)
  File "C:\Python33\lib\multiprocessing\forking.py", line 248, in __init__
    dump(process_obj, to_child, HIGHEST_PROTOCOL)
  File "C:\Python33\lib\multiprocessing\forking.py", line 166, in dump
    ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <class 'PyIID'>: attribute lookup builtins.PyIID failed

我已经查看了围绕这个问题的其他问题,但我没有清楚地解释为酸洗类实例的解决方法。

有人能证明这一点吗?

1 个答案:

答案 0 :(得分:0)

这里的问题是多处理pickles进程的参数以便传递它们。 WMI pickleable,因此不能作为参数传递给multiprocessing.Process

如果您希望这项工作,您可以:

  • 切换到使用线程而不是进程(请参阅threading模块)
  • WMI
  • 中创建monitor_created_process对象

我推荐前者,因为在创建成熟流程方面似乎没什么用处。