我有以下 Python 脚本:
import sys
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
我正在尝试从 Node.js 服务器调用此脚本,并且我已经在线阅读了两种执行此操作的方法:
第一个是使用 PythonShell:
const app = require('express')();
const ps = require('python-shell');
ps.PythonShell.run('hello.py', null, function (err, results) {
if (err) throw err;
console.log('finished');
console.log(results);
});
app.listen(4000);
当尝试以这种方式实现它时,我收到以下错误:
PythonShell.run is not a function
.
我不确定我在这里写的路径是否正确,但我确定我在服务器中写的路径是正确的。
第二种方法是使用child process:
var express = require('express');
var app = express();
app.listen(3000, function() {
console.log('server running on port 3000');
} )
app.get('/name', callName);
function callName(req, res) {
var spawn = require("child_process").spawn;
var process = spawn('python',["./hello.py",
req.query.firstname,
req.query.lastname] );
process.stdout.on('data', function(data) {
res.send(data.toString());
} )
}
当尝试这种方式时,我收到以下错误:
Error: spawn python ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:246:19) at onErrorNT (internal/child_process.js:421:16) at process.internalTickCallback (internal/process/next_tick.js:72:19) Emitted 'error' event at: at Process.ChildProcess._handle.onexit (internal/child_process.js:252:12) at onErrorNT (internal/child_process.js:421:16) at process.internalTickCallback (internal/process/next_tick.js:72:19)
有谁知道问题出在哪里吗?或者也许建议一个不同的选择?
最佳答案
看起来您提到的答案已经过时了。
试试这个:
const app = require('express')();
const {PythonShell} = require('python-shell');
PythonShell.run('hello.py', null, function (err, results) {
if (err) throw err;
console.log('finished');
console.log(results);
});
app.listen(4000);
您的第二次尝试在几个地方都是错误的。 您可以尝试以下方法:
const express = require('express');
const app = express();
const spawn = require("child_process").spawn;
app.listen(3000, () => {
console.log('server running on port 3000');
} );
app.get('/name', (req, res) => {
const firstName = req.query['firstname'],
lastName = req.query['lastname'];
if (!firstName || !lastName) {
res.status(401).send('missing-fields')
}
const process = spawn('python',["./hello.py", firstName, lastName] );
let result = '';
process.stdout.on('data', data => {
result += data.toString();
} );
process.on('close', code => {
res.send(result);
})
} );
关于python - 在 Node.js 服务器上运行 Python 脚本时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55101731/