如何从Node.js?

2024-10-03 09:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个项目制作一个Homebridge插件。Homebridge是一个节点.js我在一个模仿苹果HomeKit网桥的Raspberry Pi上运行的服务器。在

使用this链接,我可以从以下代码执行Python代码节点.js代码:

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函数(关闭设备)时,我得到以下错误,服务器退出:

^{pr2}$

是什么导致了这个错误?尤其是因为这个功能在一次使用中表现良好。在


Tags: pylogconfigdataonvarservicefunction
1条回答
网友
1楼 · 发布于 2024-10-03 09:20:19

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

py.stdin.end();

关闭流后,您不能再像在这里一样对其进行写入:

^{pr2}$

如果正在运行的Python程序通过STDIN接受多个命令,那么只需删除py.stdin.end()行。在

但是,您的Python程序很可能只运行一次就完成了。如果是这样的话,每次希望程序运行时都需要重新启动进程。在

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

相关问题 更多 >