在运行时与 nodejs 应用程序中的 python 脚本交互

Interact with python script inside nodejs application at runtime

您好,我正在尝试在 运行 时间与 nodejs 应用程序中的 python 脚本进行交互。

python 脚本更像是一个执行 whatsapp 操作的命令中心,称为 yowsup。 https://github.com/tgalal/yowsup/tree/master

我能够 运行 shell 中的 'Yowsup Cli client' 并使用它。但是我想在 nodejs 应用程序中 运行 它,因为它是用 python 编写的,而我在 python 中并不擅长。

所以我所做的就是像这样生成我通常在 shell 中使用的命令:

var spawn = require('child_process').spawn,
    ls    = spawn('./yowsup/yowsup-cli', ['demos','--login', '49XXXXXXXXXXX:8bF0hUewVcX1hf6adpuasonFdEP=', '--yowsup', '-E', 's40']);

ls.stdout.on('data', function (data) {
    console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
    console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
    console.log('child process exited with code ' + code.toString());
});

问题是,我没有从该过程中获得任何数据。 python 脚本通常会在开始时打印一些输出,但在进程 运行ning 时我无法在节点内获取任何内容。

我查看了 python 脚本,发现输出是这样生成的:

print("%s send '%s'" % (messageProtocolEntity.getFrom(False), messageProtocolEntity.getBody()))

如何在 运行 时间从 python 脚本获取一些数据?

这与您的方法略有不同,它使用 npm 库,但确实有效(resultsrandom_geo.py 脚本的标准输出):

var py = require('python-shell');
var pyOptions = {
  mode: 'text',
  pythonPath: '/opt/local/bin/python',
  scriptPath: '.'
};

function getCoords(req, res, next) {
  py.run('random_geo.py', pyOptions, function(err, results) {
    if (err) {
      console.log(err);
    } else {
      console.log(results);
    }
  });
}