简体   繁体   English

如何在Node.js中自动启动和停止python脚本?

[英]How to automatically start and stop a python script in nodejs?

I am developing a temperature monitoring application in a hen house with a web interface. 我正在通过Web界面在鸡舍中开发温度监控应用程序。 I use two arduinos and a Raspberry. 我使用两个arduinos和一个Raspberry。

Arduino 1 : I connected a temperature / humidity sensor and an RF433Mhz transmitter. Arduino 1 :我连接了温度/湿度传感器和RF433Mhz变送器。

Arduino 2 : An RF433Mhz receiver is connected to it. Arduino 2 :已连接一个RF433Mhz接收器。 It receives data from Arduino 1 . 它从Arduino 1接收数据。

Raspberry : Arduino 2 is connected to my raspberry which reads the data received in the serial monitor and send them to the web page via the websockets (package ws of nodejs). RaspberryArduino 2连接到我的Raspberry,Raspberry读取串行监视器中接收到的数据,并通过websockets (nodejs的ws包)将它们发送到网页。

At first I wanted to read this data directly with Nodejs, but I had some problems with the installation of the serial port package. 最初,我想直接使用Node.js读取此数据,但是我在安装串行端口软件包时遇到了一些问题。

So I changed my approach: I read the data in the serial monitor with python, write it in files, and Nodejs reads these files and sends the data to the web page. 因此,我改变了方法:我使用python在串行监视器中读取数据,将其写入文件中,然后Nodejs读取这些文件并将数据发送到网页。

here are the two codes I use: 这是我使用的两个代码:

Phyton script Phyton脚本

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600)

while True:
    data = ser.readline()
    if data:
        t = data[0:2]
        h = data[6:8]

        #decode utf-8
        tc = t.decode("utf-8")
        hc = h.decode("utf-8")

        #write the temperature in the temp file
        fileTc=open('temp', 'w')
        fileTc.write(str(tc))
        fileTc.close

        #write the humidity in the hum file
        fileHc=open('hum', 'w')
        fileHc.write(str(hc))
        fileHc.close

        #sleep
        time.sleep(.1)

Nodejs Script Nodejs脚本

var express = require("express");
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 4400});
var path = require("path");
var fs = require("fs");
var sys = require("util");
var exec = require("child_process").exec;

var tempcpu = 0;
var temp = 0;
var hum = 0;

var app = express();
app.set("port", process.env.PORT || 5500);

app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use('/', express.static('public'));

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
});
setInterval(function(){
    child1 = exec("cat /sys/class/thermal/thermal_zone0/temp", 
             function(error, stdout,stderr){
                if (error !== null){
                    console.log('exec error: ' +error);
                } else{
                       tempcpu = parseFloat(stdout)/1000;
                }
    });
    child2 = exec("cat temp", function(error, stdout,stderr){
            if (error !== null){
                console.log('exec error: ' +error);
            } else{
                temp = parseFloat(stdout);
            }
    });
    child3 = exec("cat hum", function(error, stdout,stderr){
            if (error !== null){
                console.log('exec error: ' +error);
            } else{
                hum = parseFloat(stdout);
            }
    });
    var tempCPU = JSON.stringify(["cpu",tempcpu]);
    var temperature = JSON.stringify(["temp",temp]);
    var humidity = JSON.stringify(["hum",hum]);

    ws.send(tempCPU);
    ws.send(temperature);
    ws.send(humidity);

    }, 5000);
});

app.get("/", function(request, response) {
   response.render("dashboard");
});

app.listen(app.get("port"), function() {
    console.log("Server started at port " + app.get("port"));
});

for now I have to launch both scripts separately. 现在,我必须分别启动两个脚本。 I would like to run my python script directly from nodejs when I start the node server, and stop it when I stop my nodejs code (CTRL + C). 我想在启动节点服务器时直接从nodejs运行python脚本,并在停止nodejs代码(CTRL + C)时停止它。

Do you have an idea of ​​how to do it? 你有一个如何做的想法吗?

What you want to achieve is spawn a new process in which you execute something from either a Node app or a Python app: 您想要实现的是产生一个新的过程,在该过程中您可以从Node应用程序或Python应用程序执行一些操作:

NodeJS approach: Child process NodeJS方法: 子进程

const { spawn } = require('child_process');
const pythonApp = spawn('python', ['my_python_app.py']);

Python approach: Subprocess Python方法: 子流程

import subprocess
node_app = subprocess.Popen(["node","my_node_app.js"], stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

EDIT 编辑

Regarding catching the INTERRUPT (CTRL+C) signal, this can also be done in both languages; 关于捕获INTERRUPT(CTRL + C)信号,也可以使用两种语言来完成。 and leveraged to kill the process you spawned: 并利用其杀死您产生的过程:

With NodeJS: 使用NodeJS:

process.on('SIGINT', () => {
    console.log("Caught interrupt signal");
    if(pythonApp) pythonApp.exit();
});

With Python: 使用Python:

import sys

try:
    # Your app here...
except KeyboardInterrupt:
    print("Caught interrupt signal")
    if node_app: node_app.kill()
    sys.exit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM