這篇文章主要介紹“Node與Python雙向通信如何實現(xiàn)”,在日常操作中,相信很多人在Node與Python雙向通信如何實現(xiàn)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Node與Python雙向通信如何實現(xiàn)”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
成都創(chuàng)新互聯(lián)公司堅持“要么做到,要么別承諾”的工作理念,服務領(lǐng)域包括:成都做網(wǎng)站、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務,滿足客戶于互聯(lián)網(wǎng)時代的榆林網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡建設(shè)合作伙伴!
第三方數(shù)據(jù)供應商把數(shù)據(jù)和Python封裝到一起,只能通過調(diào)用 Python方法來實現(xiàn)數(shù)據(jù)查詢,如果可以通過Node 簡單封裝下實現(xiàn) Python 方法調(diào)用可以快速上線并節(jié)省開發(fā)成本。
最簡單粗暴的通信方式是 Nodejs調(diào)用一下 Python 腳本,然后獲取子進程的輸出,但是由于每次 Python 啟動并加載數(shù)據(jù)包的過程比較漫長,所以對該過程優(yōu)化。
index.py
# 封裝的 Python 包, 體積巨大 from mb import MB # 從數(shù)據(jù)包中查詢 mbe.get("1.0.1.0")
index.js
const { spawn } = require("child_process"); const ls = spawn("python3", ["index.py"]); ls.stdout.on("data", (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on("data", (data) => { console.error(`stderr: ${data}`); }); ls.on("close", (code) => { console.log(`child process exited with code $[code]`); });
通過child_process.spawn來派生 Python 子進程,監(jiān)聽 stdout 輸出。上述方式也是官方文檔中的示例,目前該示例存在兩個問題:
Nodejs 沒有向 Python 發(fā)送數(shù)據(jù)
Nodejs 調(diào)用完畢后,Python 子進程會退出;下次查詢需要再次調(diào)用Python命令進行加載文件,查詢數(shù)據(jù);無法實現(xiàn)一次內(nèi)存加載,多次使用。
保證一次數(shù)據(jù)加載,多次使用的前提是 Python 進程啟動后不能退出。Python 進程之所以退出是因為無事可做,所以常見的手段有循環(huán),sleep,監(jiān)聽端口,這些手段可以翻譯成同步阻塞任務,同步非阻塞任務,其中代價最小的就是同步非阻塞任務,然后可以想到 Linux 的 select,epoll,簡單搜索了下 Python 的 epoll,好像還有原生的包。
index.py - 通過 epoll 監(jiān)聽 stdin
import sys import fcntl import select from mb import MB import json mbe = MB("./data") # epoll 模型 fd = sys.stdin.fileno() epoll = select.epoll() epoll.register(fd, select.EPOLLIN) try: while True: events = epoll.poll(10) # 同步非阻塞 data = "" for fileno, event in events: data += sys.stdin.readline() # 通過標準輸入獲取數(shù)據(jù) if data == "" or data == " ": continue items = xxx # 數(shù)處理過程 for item in items: result = mbe.get(item) sys.stdout.write(json.dumps(result, ensure_ascii=False) +" ") # 寫入到標準輸出 sys.stdout.flush() # 緩沖區(qū)刷新 finally: epoll.unregister(fd) epoll.close()
index.js - 通過 stdin 發(fā)送數(shù)據(jù)
const child_process = require("child_process"); const child = child_process.spawn("python3", ["./base.py"]); let callbacks = [], chunks=Buffer.alloc(0), chunkArr = [], data = "", onwork = false; // buffer 無法動態(tài)擴容 child.stdout.on("data", (chunk) => { chunkArr.push(chunk) if (onwork) return; onwork = true; while(chunkArr.length) { chunks = Buffer.concat([chunks, chunkArr.pop()]); const length = chunks.length; let trunkAt = -1; for(const [k, d] of chunks.entries()) { if (d == "0x0a") { // 0a 結(jié)尾 data += chunks.slice(trunkAt+1, trunkAt=k); const cb = callbacks.shift(); cb(null, data === "null" ? null : data ) data = ""; } } if (trunkAt < length) { chunks = chunks.slice(trunkAt+1) } } onwork = false; }) setInterval(() => { if (callbacks.length) child.stdin.write(` `); // Nodejs端的標準輸入輸出沒有flush方法,只能 hack, 寫入后python無法及時獲取到最新 }, 500) exports.getMsg = function getMsg(ip, cb) { callbacks.push(cb) child.stdin.write(`${ip} `); // 把數(shù)據(jù)寫入到子進程的標準輸入 }
Python 與 Nodejs 通過 stdio 實現(xiàn)通信; Python 通過 epoll 監(jiān)聽 stdin 實現(xiàn)駐留內(nèi)存,長時間運行。
Nodejs 把標準輸出作為執(zhí)行結(jié)果,故 Python 端只能把執(zhí)行結(jié)果寫入標準輸出,不能有額外的打印信息
Nodejs 端標準輸入沒有 flush 方法,所以 Python 端事件觸發(fā)不夠及時,目前通過在Nodejs端定時發(fā)送空信息來 hack 實現(xiàn)
Buffer 沒法動態(tài)擴容,沒有C語言的指針好用,在解析 stdout 時寫丑
到此,關(guān)于“Node與Python雙向通信如何實現(xiàn)”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
分享文章:Node與Python雙向通信如何實現(xiàn)
本文鏈接:http://aaarwkj.com/article42/isghec.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、全網(wǎng)營銷推廣、云服務器、網(wǎng)站排名、網(wǎng)站改版、品牌網(wǎng)站設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)