在 Node.js 中调用 Python 接口可以通过以下几种方法实现:
使用 `child_process` 模块
const { spawn } = require('child_process');
const pythonProcess = spawn('python', ['./yourScript.py', arg1, arg2]);
pythonProcess.stdout.on('data', function(data) {
console.log(data.toString());
});
pythonProcess.stderr.on('data', function(data) {
console.error(data.toString());
});
pythonProcess.on('close', function(code) {
console.log('Python process exited with code ' + code);
});
使用 `exec` 或 `execSync` 方法
const { exec } = require('child_process');
exec('python ./yourScript.py arg1 arg2', function(error, stdout, stderr) {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
// 同步执行
const result = execSync('python ./yourScript.py arg1 arg2').toString();
console.log(result);
使用第三方桥梁工具
`node-python-bridge`
`py-node`
这些工具提供了在 Node.js 和 Python 之间通信的接口。
通过 HTTP 接口调用
如果 Python 接口已经是一个 HTTP 服务,可以直接在 Node.js 中使用 `http` 或 `https` 模块发起请求。
const https = require('https');
https.get('http://localhost:5000/your-endpoint', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
选择哪种方法取决于你的具体需求,例如是否需要实时通信、是否需要跨平台支持等。希望这些方法能帮助你成功地在 Node.js 中调用 Python 接口