2011-08-18 37 views
12

Cách tốt nhất để thiết lập giao tiếp giữa hai quy trình trong python là gì? Sau khi một số googling, tôi đã cố gắng để làm như vậy:Quy trình giao tiếp bằng Python

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

gửi dữ liệu đến quá trình con:

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

Process mục tiêu chức năng:

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 

Nhưng nó dường như không làm việc (quá trình con không nhận được bất cứ điều gì thông qua parent_pipe). Làm thế nào tôi có thể sửa chữa nó?

Xin cảm ơn trước.

+0

Kiểm tra parent_pipe. Nó có bao giờ được khởi tạo không? – krs1

+0

@ krs1 Có, cả ở trẻ em và cha mẹ xử lý đường ống được khởi tạo. –

Trả lời

5

Bạn có thể xem tại đây: http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes Giải pháp gần với bạn nhưng có vẻ dễ dàng hơn.

+0

Vấn đề là giải pháp này không hiệu quả đối với tôi vì một số lý do. Tôi không thể đọc bất cứ điều gì từ đường ống mặc dù dữ liệu được gửi đi. –

+0

Tôi đoán vấn đề là với quá trình khởi tạo của bạn. Tham số 'target' được sử dụng để liên kết một hàm với phần cuối của đường ống. – Tom97531

0

Nếu tôi hiểu tài liệu, trong quá trình con bạn nên đọc từ phần con của đường ống.

# 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 
Các vấn đề liên quan