我需要知道如何执行Python shell命令并获得恒定的输出

问题描述 投票:0回答:1

抱歉我的英语不好

我正在创建一面魔镜,并为此开发一个模块。我用 python 做了一个脚本,我需要不断打印脚本的 shell,因为它是一个“While True”。为此,我需要执行一个子进程,但我的问题是:当我的脚本运行时,它不会在日志控制台或镜像中打印任何内容。

文件

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)
        }
})

非常感谢您抽出时间!

注意:如果我的Python脚本没有“while true”(只有一个序列),它就可以工作,只有当我的脚本未定义时才不起作用

javascript python magic-mirror
1个回答
0
投票

Ofc我不知道你如何使用导出的模块,但我假设你只是运行启动函数来阻止你的进程,但正如文档所说,

spawn
是异步的,不会阻止循环,并且你添加了异步函数,这使得这是一个承诺。

因此,如果您希望它是异步的,您必须正确处理当前模块以及调用它的所有其他模块中的承诺:

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)
        }
})

或者简单地使用阻塞版本生成子进程:https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options 这应该更简单

© www.soinside.com 2019 - 2024. All rights reserved.