【问题标题】:Return result from python script in Node JS child process从 Node JS 子进程中的 python 脚本返回结果
【发布时间】:2020-11-28 20:18:10
【问题描述】:

我试图从 nodejs 子进程的 python 脚本返回值,但我似乎无法让它工作,它使用 console.log 在控制台中正确打印,但只返回未定义,我想知道如果有办法直接返回该值,或者将 console.log 结果解析为字符串。

var sys = require('util');
module.exports = function() {
    this.getPlay = function getPlaylist(name) {
        const childPython = spawn('python' ,['main.py', name]);
        var result = '';
        childPython.stdout.on(`data` , (data) => {
            result += data.toString();

        });
    
        childPython.on('exit' , () => {
            console.log(result);
        
        });
        
    }};

Python 脚本暂时为空,并打印“Hello 'name'” 编辑: 我尝试使用承诺,这就是我所拥有的:

    (async function(){
        function test(name) {
            return new Promise((resolve , reject) => {
                const childPython = spawn('python' ,['main.py', "He"]);
                var result = '';
                childPython.stdout.on(`data` , (data) => {
                    result += data.toString();
                });
            
                childPython.on('close' , function(code) {
                    t = result
                    resolve(result)
                });
                childPython.on('error' , function(err){
                    reject(err)
                });
        
            })};
        
        var t;
        await test(name);
        console.log(t);
        return t;
        })();

【问题讨论】:

  • 你也可以发布你的python脚本吗?你从 python 中返回了什么以及如何返回?
  • @kg99 现在只是打印 hello 'name' ,试图了解它是如何工作的
  • 那么你的代码应该可以工作了。只需在您的 python 脚本中仅打印“hello”进行测试。缓冲区应该收集输出数据。只需将其称为 const childPython = spawn('python' ,['main.py']);。我认为您在脚本中做错了什么。
  • @kg99 它工作正常,但它只在控制台中打印结果,我想将该结果发送到一个变量中以在我的代码中的其他地方使用
  • 您已将其存储在结果中。你能添加console.log(results)吗?

标签: node.js


【解决方案1】:

这样定义。

 function getPlaylist(name) {
      return new Promise((resolve , reject) => {
          const childPython = spawn('python' ,['main.py', name]);
          var result = '';
          childPython.stdout.on(`data` , (data) => {
              result += data.toString();
          });
      
          childPython.on('close' , function(code) {
              resolve(result)
          });
          childPython.on('error' , function(err){
              reject(err)
          });
  
      })
    };

记住使用 try...catch 它会被拒绝。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

async function runTest() {
  try {
    const playList = await getPlaylist();
    console.log(playList);
  } catch (err) {

  }
}
 
runTest()

【讨论】:

  • 所以,如果我想操作字符串 playList,我是否只需为 runTest() 设置一个变量 = 并对其进行操作?
  • 是的。你可以对变量做任何事情。
【解决方案2】:
const {spawn} = require('child_process');

const getPythonScriptStdout = (pythonScriptPath) => {
    const python = spawn('python', [pythonScriptPath]);
    return new Promise((resolve, reject) => {
        let result = ""
        python.stdout.on('data', (data) => {
            result += data
        });
        python.on('close', () => {
            resolve(result)
        });
        python.on('error', (err) => {
            reject(err)
        });
    })
}


getPythonScriptStdout('./python.py').then((output) => {
    console.log(output)
})

python.py 文件

print("hi from python")

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 2012-08-21
    • 2020-06-20
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2020-08-13
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多