gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:07:47 25 4
gpt4 key购买 nike

我正在制作一个 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)

什么可能导致此错误?特别是因为该功能对于单次使用来说似乎工作得很好。

最佳答案

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

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']);
...
}

关于javascript - 如何从 Node.js 调用 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39458333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com