node.js - Node.js 子进程运行 python 代码没有响应
问题描述
我有一个 Express Node.js 应用程序,但我想运行 python 代码(发送数据和接收结果)但是当我使用邮递员测试它时仍在加载并且我没有任何响应。
我的 node.js 代码
router.get('/name', callName);
function callName(req, res) {
var exec = require("child_process").exec;
var process = exec('python',["./hello.py",
req.query.firstname,
req.query.lastname
] );
process.stdout.on('data', function(error,data) {
console.log('stderr: ', error);
res.send(data.toString());
} )
}
蟒蛇代码
import sys
# Takes first name and last name via command
# line arguments and then display them
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
# Save the script as hello.py
谢谢@nijm 我找到了解决方案
首先 child_process.exec 方法不接受作为数组的命令参数(就像 child_process.spawn 一样)。
第二,
你必须在你的机器上安装 python。
第三
你必须在公共文件夹中有python文件(在我的情况下上传文件夹)
所有这些步骤都没有在任何教程或关于如何从 Node.js 调用 Python 函数的示例中提及
归根结底,我的代码是
router.get('/name', callName);
function callName(req, res) {
var exec = require("child_process").exec;
exec(`python uploads/hello.py ${req.query.firstname} ${req.query.lastname}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
}
蟒蛇代码
import sys
# Takes first name and last name via command
# line arguments and then display them
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
# Save the script as hello.py
解决方案
该child_process.exec
方法不接受命令参数作为数组(就像这样child_process.spawn
做),试试这个(未经测试):
var exec = require("child_process").exec;
exec(`python ./hello.py ${req.query.firstname} ${req.query.lastname}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
推荐阅读
- azure-ad-b2c - 自动 URL 重定向到 Azure AD B2C 应用程序
- php - PHP mb_substr() 调用未定义函数
- machine-learning - 在 Keras 中使用深度学习的不同结果
- neo4j - 在 neo4j 中合并/创建 UNWIND
- sorting - 在 ONGR ElasticsearchDSL 中按距离对结果进行排序
- javascript - 隐藏位置相对父位置之外的绝对位置元素
- javascript - TypeScript 简写“如果”
- mongodb - 使用 --nsFrom 和 --nsTo 从未知数据库名称恢复到不同的数据库
- mongodb - 如何在没有猫鼬的情况下将 mongodb 与 graphql 连接
- angular - Angular 5 Webpack 编译成功但主页未加载