在 aws lambda 上使用 child_process spawn 作为 python 脚本

2024-01-04

我试图通过 child_process.spawn 系统使用我的 javascript 文件运行 python 脚本,但它似乎永远不会在 aws lambda 上运行。

相关代码是:

getEntities: function (){
    var spawn = require('child_process').spawn;
    var py = spawn('python', ['mainPythonFile.py']);
    var outputString = "starting string";

    console.log("BEFORE ANY INPUT");
    py.stdout.on('data', function (data) {
        console.log("----Getting information from the python script!---");
        outputString += data.toString();
        console.log(outputString);
    });

    py.stdout.on('end', function (){
        console.log("===hello from the end call in python files===");
        console.log("My output : " + outputString);
    });
    console.log("NO INPUT CHANGED??");

    return outputString;

}

这些文件位于文件夹结构的同一级别(表面级别)。

正在运行的 python 文件非常简单,只包含一些打印语句:

主要Python文件:

import sys;
print("Hello There");
print("My name is Waffles");
print("Potato Waffles");
sys.stdout.flush()

The output我从 aws 服务得到的是这样的:

BEFORE ANY INPUT
NO INPUT CHANGED??
starting string

我尝试了不同的路径来尝试访问 python 文件,例如*mainPythonFile.py ./mainPythonFile.py etc.

我觉得代码似乎没问题,因为这适用于我的本地计算机,但是尝试让它在 AWS 上运行有一个我无法理解的微妙之处。

如果需要,我可以提供任何其他信息。

注意:“getEntities”函数正在被另一个node.js 文件调用,但我将代码移至调用函数,得到了相同的结果。


由于 JS 的异步特性,正如 Chris 所解释的,该函数在实际调用派生线程中的“end”之前到达“return”语句。

这意味着代码永远没有机会实际设置正确的输出文本。

我更改了函数调用以接受回调,然后当程序回复信息时回调会做出响应。

我的新功能对此略有改变(没有打印):

getEntities: function(callbackFunction, that){
var spawn = require('child_process').spawn;
var py = spawn('python', ['mainPythonFile.py']);
var outputString = "starting string";

py.stdout.on('data', function (data) {
    outputString += data.toString();
});
// that = "this == alexa" that's passed in as input.
py.stdout.on('end', function (){
    callbackFunction(outputString, that);
});

调用该函数的函数现在如下:

HelperFunctions.getEntities(function(returnString,that){
  that.response.speak(returnString);
  that.emit(':responseReady');
}, this);

我确信有一种更漂亮的方法可以做到这一点,但这似乎目前有效。感谢克里斯G

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 aws lambda 上使用 child_process spawn 作为 python 脚本 的相关文章

随机推荐