Python中的进程通信

问题描述:

在python中建立两个进程之间的通信的最佳方式是什么?一些google搜索后,我试着这样做:Python中的进程通信

parent_pipe, child_pipe = Pipe() 
p = Process(target = instance_tuple.instance.run(), \ 
    args = (parent_pipe, child_pipe,)) 
p.start() 

将数据发送到子进程:

command = Command(command_name, args) 
parent_pipe.send(command) 

过程的目标函数:

while True: 
    if (self.parent_pipe.poll()): 
     command = parent_pipe.recv() 
     if (command.name == 'init_model'): 
      self.init_model() 
     elif (command.name == 'get_tree'): 
      tree = self.get_fidesys_tree(*command.args) 
      result = CommandResult(command.name, tree) 
      self.child_pipe.send(result) 
     elif(command.name == 'set_variable'): 
      name = command.args[0] 
      value = command.args[1] 
      self.config[name] = value 

但它似乎不工作(子进程通过parent_pipe没有收到任何东西)。我该如何解决它?

在此先感谢。

+0

检查parent_pipe。它是否被实例化? – krs1

+0

@ krs1是的,无论是在子进程还是父进程中,管道都被实例化。 –

你可以看看这里:http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes 该解决方案接近你的,但似乎更容易。

+0

事情是这个解决方案由于某种原因不适合我。尽管数据已发送,但我无法从管道读取任何内容。 –

+0

我想问题是你的实例化过程。参数'target'用于将函数链接到管道的末端。 – Tom97531

如果我理解文档,在子进程中,您应该从管道的子部分读取。

# Process Target function 

while True: 
     # poll(None) because you don't want to go through the loop fast between commands 
     if (self.child_pipe.poll(None)):  
      command = child_pipe.recv() 
      if (command.name == 'init_model'): 
       self.init_model() 
      elif (command.name == 'get_tree'): 
       tree = self.get_fidesys_tree(*command.args) 
       result = CommandResult(command.name, tree) 
       self.child_pipe.send(result) 
      elif(command.name == 'set_variable'): 
       name = command.args[0] 
       value = command.args[1] 
       self.config[name] = value