Node.js 与 Python 混合编程

有一个需求是做一个基于 Node.js 的程序化股票交易功能。
既然 Python 已经有现成的 easytrader、easyquotation ,那就不要再去重复造轮子。

image.png
main.py

import sys, json, easyquotation

for line in sys.stdin:    
    quotation = easyquotation.use('sina')
    stockList = quotation.stocks(json.loads(line), prefix=True)

    print(json.dumps(stockList))
index.js

const { PythonShell } = require('python-shell');

let options = {
    mode: 'json',
    pythonPath: '/usr/local/bin/python3',
};

const shell = new PythonShell('main.py', options);

shell.send(['600000', '300001']);

shell.on('message', function (message) {
    console.log(message);
});

shell.end(() => {
    console.log('执行完毕');
});

主要使用 python-shell 这个库

$ sudo node index.js

{ sh600000: 
   { name: '"浦发银行',
     open: 10.31,
     close: 10.37,
     now: 10.22,
     high: 10.37,
     low: 10.21,
     buy: 10.22,
     sell: 10.23,
     turnover: 8683386,
     volume: 89312973,
     bid1_volume: 76499,
     bid1: 10.22,
     bid2_volume: 577300,
     bid2: 10.21,
     bid3_volume: 537400,
     bid3: 10.2,
     bid4_volume: 117600,
     bid4: 10.19,
     bid5_volume: 99400,
     bid5: 10.18,
     ask1_volume: 1300,
     ask1: 10.23,
     ask2_volume: 61400,
     ask2: 10.24,
     ask3_volume: 101500,
     ask3: 10.25,
     ask4_volume: 4600,
     ask4: 10.26,
     ask5_volume: 10000,
     ask5: 10.27,
     date: '2018-09-05',
     time: '13:02:03' },
  sz300001: 
   { name: '"特锐德',
     open: 12.45,
     close: 12.46,
     now: 12.25,
     high: 12.59,
     low: 12.25,
     buy: 12.25,
     sell: 12.28,
     turnover: 808133,
     volume: 9987551.22,
     bid1_volume: 6100,
     bid1: 12.25,
     bid2_volume: 1400,
     bid2: 12.24,
     bid3_volume: 2300,
     bid3: 12.23,
     bid4_volume: 8400,
     bid4: 12.22,
     bid5_volume: 33200,
     bid5: 12.21,
     ask1_volume: 1500,
     ask1: 12.28,
     ask2_volume: 40100,
     ask2: 12.3,
     ask3_volume: 3600,
     ask3: 12.31,
     ask4_volume: 1000,
     ask4: 12.32,
     ask5_volume: 2000,
     ask5: 12.33,
     date: '2018-09-05',
     time: '13:02:00' } }
执行完毕

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python资源大全中文版,包括:Web框架、网络爬虫、模板引擎、数据库、数据可视化、图片处理等,由伯乐在线持续更...
    dxl1236阅读 4,724评论 2 33
  • 英文原版:https://github.com/vinta/awesome-python中文版:https://g...
    会灰的大飞狼阅读 3,635评论 1 56
  • 革命尚未成功,同志仍需努力💪 1、导读 1) 泛型编程(Generic Programming)和面向对象编程(O...
    hello萌面大婶阅读 98评论 0 0
  • 完成:硬本领1(10) 这两天感觉自己有点松懈,没有以前那么积极,疲劳期到了?要调整。知道到拥有还有一个过程去...
    莺子_3f93阅读 78评论 0 0
  • 今天便是跨入31岁的第一天 这时刻回想这几年来 有过许多不如意 茫然 也不知未来 等孩子睡下 翻出许久不曾看过的 ...
    风之奕帆阅读 342评论 0 0