2011-08-18 85 views
12

在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是的,無論是在子進程還是父進程中,管道都被實例化。 –

回答

0

如果我理解文檔,在子進程中,您應該從管道的子部分讀取。

# 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