天天看點

python3,程序間的通信

本文來源于 python 3.5版本的官方文檔 multiprocessing子產品為程序間通信提供了兩種方法:

1.程序隊列queue

The Queue class is a near clone of queue.Queue。
Queues are thread and process safe。           

使用程序隊列,可以在兩個程序間傳遞消息。其用法跟queue.Queue類似。

使用方法:

from multiprocessing import Process,Queue
def func(q):
    q.put([42,None,"hello"])    #把一個清單放入一個隊列中

if __name__=="__main__":
    q1=Queue()        #定義一個隊列
    p1=Process(target=func,args=(q1,))      #執行個體化一個程序
    p1.start()  #啟動程序 
    print(q1.get())     #從隊列中取出一個項目,并列印 
    p1.join()   #阻塞程序           

傳回值:

[42, None, 'hello']           

在程序間通信可以使用python中所有的資料類型,但這種方式并不是真正意義上的程序間的通信。

2.管道pipe

The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex (two-way).
The two connection objects returned by Pipe() represent the two ends of the pipe. Each connection object has send() and recv() methods (among others).
Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time. 
Of course there is no risk of corruption from processes using different ends of the pipe at the same time.           

pipe()傳回兩個連接配接對象代表pipe的兩端。每個連接配接對象都有send()方法和recv()方法。

但是如果兩個程序或線程對象同時讀取或寫入管道兩端的資料時,管道中的資料有可能會損壞。

當程序使用的是管道兩端的不同的資料則不會有資料損壞的風險。

from multiprocessing import Process,Pipe

def func(conn):
    conn.send([42,None,"hello"])    #連接配接發出資訊
    conn.close()        #關閉連接配接 

if __name__=="__main__":
    parent_conn,child_conn=Pipe()       #定義一個管道
    p1=Process(target=func,args=(child_conn,))  #執行個體化一個程序
    p1.start()      #啟動程序 
    print(parent_conn.recv())       #連接配接接收資訊并列印
    p1.join()   #阻塞程序            

傳回結果:

[42, None, 'hello']