python實現(xiàn)跨進程(跨py文件)通信示例
前言
項目中總會遇到數(shù)據(jù)需要跨進程通信的問題,今天就給大家?guī)硪惶缀唵蔚目邕M程通信代碼。代碼分為服務(wù)端與客戶端兩部分。
一、server端
import multiprocessing
import time
def do_socket(conn, addr, ):
try:
while True:
if conn.poll(1) == False:
time.sleep(0.5)
continue
data = conn.recv() # 等待接受數(shù)據(jù)
conn.send('sucess')
# ***********************
# 要執(zhí)行的程序?qū)懺谶@里
# ***********************
print(data)
except Exception as e:
print('Socket Error', e)
finally:
try:
conn.close()
print('Connection close.', addr)
except:
print('close except')
def run_server(host, port):
from multiprocessing.connection import Listener
server_sock = Listener((host, port))
print("Sever running...", host, port)
pool = multiprocessing.Pool(10)
while True:
# 接受一個新連接:
conn = server_sock.accept()
addr = server_sock.last_accepted
print('Accept new connection', addr)
# 創(chuàng)建進程來處理TCP連接:
pool.apply_async(func=do_socket, args=(conn, addr,))
if __name__ == '__main__':
server_host = '127.0.0.1'
server_port = 8000
run_server(server_host, server_port)
二、client端
import time
from multiprocessing.connection import Client
client = Client(('127.0.0.1', 8000))
while True:
data = 'send data'
client.send(data)
data = client.recv() # 等待接受數(shù)據(jù)
print(data)
time.sleep(1)
這里只是給了client端的示例代碼,實際通信的數(shù)據(jù)類型可以是多樣的(字符串、數(shù)字、圖片等)
三、運行效果
先運行server端,再運行client端。
server端

client端

總結(jié)
本文簡單給大家提供了一套簡單封裝的跨進程通信代碼,方便大家快速上手實現(xiàn)跨進程通信,有需要的伙伴可以根據(jù)自己的需求調(diào)整代碼。
到此這篇關(guān)于python實現(xiàn)跨進程(跨py文件)通信示例的文章就介紹到這了,更多相關(guān)python 跨進程通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
YOLOv5在圖片上顯示統(tǒng)計出單一檢測目標的個數(shù)實例代碼
各位讀者首先要認識到的問題是,在YOLOv5中完成錨框計數(shù)是一件非常簡單的工作,下面這篇文章主要給大家介紹了關(guān)于YOLOv5如何在圖片上顯示統(tǒng)計出單一檢測目標的個數(shù)的相關(guān)資料,需要的朋友可以參考下2023-03-03
python3 實現(xiàn)的對象與json相互轉(zhuǎn)換操作示例
這篇文章主要介紹了python3 實現(xiàn)的對象與json相互轉(zhuǎn)換操作,結(jié)合實例形式分析了Python3使用json模塊針對json格式數(shù)據(jù)轉(zhuǎn)換操作的相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2019-08-08

