Node與Python 雙向通信的實現代碼
第三方數據供應商把數據和Python封裝到一起,只能通過調用 Python方法來實現數據查詢,如果可以通過Node 簡單封裝下實現 Python 方法調用可以快速上線并節省開發成本。
最簡單粗暴的通信方式是 Nodejs調用一下 Python 腳本,然后獲取子進程的輸出,但是由于每次 Python 啟動并加載數據包的過程比較漫長,所以對該過程優化。
進程通信index.py
# 封裝的 Python 包, 體積巨大from mb import MB# 從數據包中查詢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 子進程,監聽 stdout 輸出。上述方式也是官方文檔中的示例,目前該示例存在兩個問題:
Nodejs 沒有向 Python 發送數據Nodejs 調用完畢后,Python 子進程會退出;下次查詢需要再次調用Python命令進行加載文件,查詢數據;無法實現一次內存加載,多次使用。進程雙向通信保證一次數據加載,多次使用的前提是 Python 進程啟動后不能退出。Python 進程之所以退出是因為無事可做,所以常見的手段有循環,sleep,監聽端口,這些手段可以翻譯成同步阻塞任務,同步非阻塞任務,其中代價最小的就是同步非阻塞任務,然后可以想到 Linux 的 select,epoll,簡單搜索了下 Python 的 epoll,好像還有原生的包。
index.py - 通過 epoll 監聽 stdin
import sysimport fcntlimport selectfrom mb import MBimport jsonmbe = 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() # 通過標準輸入獲取數據 if data == ’’ or data == ’n’:continue items = xxx # 數處理過程 for item in items:result = mbe.get(item)sys.stdout.write(json.dumps(result, ensure_ascii=False) +’n’) # 寫入到標準輸出sys.stdout.flush() # 緩沖區刷新finally: epoll.unregister(fd) epoll.close()
index.js - 通過 stdin 發送數據
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 無法動態擴容 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 結尾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(`n`); // Nodejs端的標準輸入輸出沒有flush方法,只能 hack, 寫入后python無法及時獲取到最新}, 500)exports.getMsg = function getMsg(ip, cb) { callbacks.push(cb) child.stdin.write(`${ip}n`); // 把數據寫入到子進程的標準輸入}
Python 與 Nodejs 通過 stdio 實現通信; Python 通過 epoll 監聽 stdin 實現駐留內存,長時間運行。
存在問題 Nodejs 把標準輸出作為執行結果,故 Python 端只能把執行結果寫入標準輸出,不能有額外的打印信息 Nodejs 端標準輸入沒有 flush 方法,所以 Python 端事件觸發不夠及時,目前通過在Nodejs端定時發送空信息來 hack 實現 Buffer 沒法動態擴容,沒有C語言的指針好用,在解析 stdout 時寫丑總結雖然可以實現 Nodejs 和 Python 的雙向通信,然后由于上述種種問題,在這里并不推薦使用這種方式,通過 HTTP 或 Socket 方式比這個香多了。
到此這篇關于Nodejs與Python 雙向通信的實現代碼的文章就介紹到這了,更多相關Nodejs與Python雙向通信內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: