使用serverless框架和this作为指南发布,我想从 python 脚本中打印出一些信息,我的 handler.js 中有相关的代码
const path = await require('path')
const { spawn } = await require('child_process')
/**
* Run python script, pass in `-u` to not buffer console output
* @return {ChildProcess}
*/
runScript() {
return spawn('python', [
"-u",
path.join(__dirname, 'script.py'),
"--foo", "some value for foo",
]);
}
const subprocess = await runScript()
// print output of script
await subprocess.stdout.on('data', (data) => {
console.log(`data:${data}`);
});
await subprocess.stderr.on('data', (data) => {
console.log(`error:${data}`);
});
await subprocess.stderr.on('close', () => {
console.log("Closed");
});
我还有script.py
#!/usr/bin/python
import sys, getopt, time
def main(argv):
argument = ''
usage = 'usage: script.py -f <sometext>'
# parse incoming arguments
try:
opts, args = getopt.getopt(argv,"hf:",["foo="])
except getopt.GetoptError:
print(usage)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print(usage)
sys.exit()
elif opt in ("-f", "--foo"):
argument = arg
# print output
print("Start : %s" % time.ctime())
time.sleep( 5 )
print('Foo is')
time.sleep( 5 )
print(argument)
print("End : %s" % time.ctime())
if __name__ == "__main__":
main(sys.argv[1:])
当我调用处理程序函数时,我希望控制台显示输出或错误,但它什么也不打印
最佳答案
这样做的方法是:
const path = require("path");
const { spawn } = require("child_process");
const runScript = () => {
return spawn("python", [
"-u",
path.join(__dirname, "script.py"),
"--foo",
"some value for foo"
]);
};
const promise = new Promise((resolve, reject) => {
const subprocess = runScript();
subprocess.stdout.on("data", data => {
console.log(`data:${data}`);
});
subprocess.stderr.on("data", data => {
console.log(`error:${data}`);
});
subprocess.on("close", code => {
if (code !== 0) {
reject(code);
} else {
resolve(code);
}
});
});
await promise;
无需使用 await
来实现同步函数,通过使用 Promise 包装 subprocess
,您可以对其进行 await
。
关于python - Node : Using child process in aws lambda to run python script not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57594671/