I need to know how to execute python shell comand and get constant output

319 Views Asked by At

(sorry for my bad english), Im making a Magic Mirror and Im developing a Module for that. I had done a script in python and I need to print consantly the shell of the script because is a "While True". For that I need to do a child process but my problem is: while my script is running it doest print anything in the log console or the mirror.

The file of node_helper.js --->

var NodeHelper = require("node_helper")
var { spawn } = require("child_process")

var self = this

async function aexec() {
        const task = spawn('python3', ['/Fotos/reconeixementfacial.py'])
        task.stdout.on('data', (data) => {
                console.log(`${data}`)
        })
        task.stdout.on('exit', (data) => {
                console.log("exit")
        })
        task.stdout.on('error', (data) => {
                console.log(`${error}`)
        })
        task.unref()
}

module.exports = NodeHelper.create({
        start: function() {
                aexec()
        },
        socketNotificationReceived: function(notification, payload) {
                console.log(notification)
        }
})

Thank you so much for the time !! Note: If my python script doesnt have a "while true" (only a sequence), it works, only doesnt work if my script is undifined

1

There are 1 best solutions below

6
Vitalik Teremasov On

Ofc I don't know how you use the exported module but I assume you just run the start function to block your process but as Docs say spawn is async and doesn't block the loop and you added the async function which made it a promise.

So if you want it to be async you have to properly handle promises in the current module and all others which call it:

var NodeHelper = require("node_helper")
var { spawn } = require("child_process")

var self = this

function aexec() {
    return new Promise(function(resolve, reject) {
        let result = '';
        const task = spawn('python3', ['/Fotos/reconeixementfacial.py'])
        task.stdout.on('data', (data) => {
                console.log(`${data}`)
                result += data.toString() // accumulate
        })
        task.stdout.on('exit', (data) => {
                console.log("exit")
                task.unref()
                resolve(result) // return from promise (async)
        })
        task.stdout.on('error', (data) => {
                console.log(`${error}`)
                task.unref()
                reject()
        })
    });
}

module.exports = NodeHelper.create({
        start: function() {
                aexec().then((result) => console.log(result))
        },
        socketNotificationReceived: function(notification, payload) {
                console.log(notification)
        }
})

Or simple use blocking version of spawning a child process: https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options Which should be much simpler