管道是双向通信的,数据从其中一端传入,就会从另外一端传出。
from multiprocessing import Pipe c1, c2 = Pipe() c1.send(123) print(c2.recv()) # 一端进去,从另一端接收。
在进程间通过管道实现通信。
from multiprocessing import Pipe from multiprocessing import Process def func(conn): conn.send(111) if __name__ == "__main__": conn1, conn2 = Pipe() p = Process(target=func, args=(conn1,)) p.start() print(conn2.recv())
多次发数据:
from multiprocessing import Process from multiprocessing import Pipe def func(conn): while 1: msg = conn.recv() if msg == None:break print(msg) if __name__ == "__main__": conn1, conn2 = Pipe() Process(target=func, args=(conn1,)).start() for i in range(20): conn2.send(111) conn2.send(None)
另一种方式close():
from multiprocessing import Process from multiprocessing import Pipe def func(conn1, conn2): conn2.close() # conn2传过来不用,直接关掉 while 1: try: msg = conn1.recv() print(msg) except EOFError: # 捕获这个报错,关掉conn1并结束.EOFError是没有数据了还要recv时报的错 conn1.close() break if __name__ == "__main__": conn1, conn2 = Pipe() Process(target=func, args=(conn1, conn2)).start() conn1.close() # 关掉conn1 for i in range(20): conn2.send(111) conn2.close() # 关掉conn2