我需要知道如何执行pythonshellcomand并获得恒定的输出

2024-09-21 03:26:42 发布

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

(很抱歉我的英语不好),我正在制作一个魔镜,我正在为此开发一个模块。我用python编写了一个脚本,我需要打印脚本的外壳,因为它是“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”(只有一个序列),那么它可以工作,只有在我的脚本没有定义的情况下才会工作


Tags: helper脚本lognodetaskdataonvar
1条回答
网友
1楼 · 发布于 2024-09-21 03:26:42

Ofc我不知道如何使用导出的模块,但我假设您只是运行start函数来阻止您的进程,但正如文档所说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 这应该简单得多

相关问题 更多 >

    热门问题