- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) > JavaScript >
- Node與Python 雙向通信的實(shí)現代碼
第三方數據供應商把數據和Python封裝到一起,只能通過(guò)調用 Python方法來(lái)實(shí)現數據查詢(xún),如果可以通過(guò)Node 簡(jiǎn)單封裝下實(shí)現 Python 方法調用可以快速上線(xiàn)并節省開(kāi)發(fā)成本。
最簡(jiǎn)單粗暴的通信方式是 Nodejs調用一下 Python 腳本,然后獲取子進(jìn)程的輸出,但是由于每次 Python 啟動(dòng)并加載數據包的過(guò)程比較漫長(cháng),所以對該過(guò)程優(yōu)化。
index.py
# 封裝的 Python 包, 體積巨大 from mb import MB # 從數據包中查詢(xún) 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]`); });
通過(guò)child_process.spawn來(lái)派生 Python 子進(jìn)程,監聽(tīng) stdout 輸出。上述方式也是官方文檔中的示例,目前該示例存在兩個(gè)問(wèn)題:
保證一次數據加載,多次使用的前提是 Python 進(jìn)程啟動(dòng)后不能退出。Python 進(jìn)程之所以退出是因為無(wú)事可做,所以常見(jiàn)的手段有循環(huán),sleep,監聽(tīng)端口,這些手段可以翻譯成同步阻塞任務(wù),同步非阻塞任務(wù),其中代價(jià)最小的就是同步非阻塞任務(wù),然后可以想到 Linux 的 select,epoll,簡(jiǎn)單搜索了下 Python 的 epoll,好像還有原生的包。
index.py - 通過(guò) epoll 監聽(tīng) 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() # 通過(guò)標準輸入獲取數據 if data == '' or data == '\n': continue items = xxx # 數處理過(guò)程 for item in items: result = mbe.get(item) sys.stdout.write(json.dumps(result, ensure_ascii=False) +'\n') # 寫(xiě)入到標準輸出 sys.stdout.flush() # 緩沖區刷新 finally: epoll.unregister(fd) epoll.close()
index.js - 通過(guò) stdin 發(fā)送數據
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 無(wú)法動(dòng)態(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 結尾 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端的標準輸入輸出沒(méi)有flush方法,只能 hack, 寫(xiě)入后python無(wú)法及時(shí)獲取到最新 }, 500) exports.getMsg = function getMsg(ip, cb) { callbacks.push(cb) child.stdin.write(`${ip}\n`); // 把數據寫(xiě)入到子進(jìn)程的標準輸入 }
Python 與 Nodejs 通過(guò) stdio 實(shí)現通信; Python 通過(guò) epoll 監聽(tīng) stdin 實(shí)現駐留內存,長(cháng)時(shí)間運行。
雖然可以實(shí)現 Nodejs 和 Python 的雙向通信,然后由于上述種種問(wèn)題,在這里并不推薦使用這種方式,通過(guò) HTTP 或 Socket 方式比這個(gè)香多了。
到此這篇關(guān)于Nodejs與Python 雙向通信的實(shí)現代碼的文章就介紹到這了,更多相關(guān)Nodejs與Python雙向通信內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站