如何从Node.js调用Python函数?

时间:2016-09-12 20:29:16

标签: javascript python node.js

我正在为项目制作Homebridge插件。 Homebridge是一个Node.js服务器,我在Raspberry Pi上运行,模拟Apple HomeKit Bridge。

使用this链接,我能够从以下Node.js代码执行Python代码:

var Service, Characteristic;

var spawn = require('child_process').spawn;
var py = spawn('python', ['/home/pi/Desktop/RFbulb/nRF24L01PLUS.py']);
var data = [10,10,10];
var dataString = '';

var RFstatus = true;

module.exports = function(homebridge) {
    Service = homebridge.hap.Service;
    Characteristic = homebridge.hap.Characteristic;

    homebridge.registerAccessory("homebridge-RFbulb", "RFbulb", RFbulbAccessory);
}

function RFbulbAccessory(log, config) {
    this.log = log;
    this.config = config;
    this.name = config["name"];
    this.address = config["address"];

    this.service = new Service.Lightbulb(this.name);
    this.service
        .getCharacteristic(Characteristic.On)
        .on('get', this.getOn.bind(this))
        .on('set', this.setOn.bind(this));
}

RFbulbAccessory.prototype.setOn = function(on, callback) { // This is the function throwing the error
    var state = on ? "on": "off";
    if (state == "on") {
        data = [1,parseInt(this.address, 10),100];
        dataString = '';
        py.stdout.on('data', function(data) {
            dataString += data.toString();
        });
        py.stdout.on('end', function() {
            console.log(dataString);
        });
        py.stdin.write(JSON.stringify(data));
        py.stdin.end();
        RFstatus = true;
    }
    callback(null);
}

RFbulbAccessory.prototype.getServices = function() {
    return [this.service];
}

有趣的是,当我第一次激活setOn功能时(例如,打开设备)它工作正常,但是当我第二次激活setOn功能时(转向设备关闭)我收到以下错误,服务器退出:

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: write after end
    at writeAfterEnd (_stream_writable.js:166:12)
    at Socket.Writable.write (_stream_writable.js:211:5)
    at Socket.write (net.js:642:40)
    at RFbulbAccessory.setOn (/usr/lib/node_modules/homebridge-RFbulb/index.js:47:12)
    at emitThree (events.js:97:13)
    at emit (events.js:175:7)
    at Characteristic.setValue (/usr/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/Characteristic.js:155:10)
    at Bridge.<anonymous> (/usr/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/Accessory.js:710:22)
    at Array.forEach (native)
    at Bridge.Accessory._handleSetCharacteristics (/usr/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/Accessory.js:655:8)

可能导致此错误的原因是什么?特别是因为该功能似乎只能在一次使用中正常工作。

1 个答案:

答案 0 :(得分:1)

您收到该错误是因为您正在关闭输入流:

py.stdin.end();

关闭流后,您就不能再像以前那样写信了:

py.stdin.write(JSON.stringify(data));

如果您运行的Python程序接受STDIN上的多个命令,则只需删除py.stdin.end()行。

但是,您的Python程序可能会运行一次然后完成。如果是这种情况,则每次希望程序运行时都需要重新生成该过程。

if (state === "on") {
    py = spawn('python', ['/home/pi/Desktop/RFbulb/nRF24L01PLUS.py']);
    ...
}