要通过 Node.js 运行 Python 文件,可以采用多种方法,其中最常用和便捷的方式是使用 child_process
模块。下面将详细介绍几种常见的方法,并提供相应的代码示例。
child_process.exec
或 child_process.spawn
exec
exec
方法适用于执行简单的命令,并获取输出结果。它会在执行完命令后将结果缓冲起来并传递给回调函数。
javascriptconst { exec } = require('child_process');
// 假设有一个名为 script.py 的 Python 文件
exec('python script.py', (error, stdout, stderr) => {
if (error) {
console.error(`执行错误: ${error.message}`);
return;
}
if (stderr) {
console.error(`标准错误: ${stderr}`);
return;
}
console.log(`标准输出:\n${stdout}`);
});
spawn
spawn
方法适用于需要处理大量数据输出的场景,因为它不会对输出进行缓冲,而是通过流的方式处理数据。
javascriptconst { spawn } = require('child_process');
// 创建一个子进程来执行 Python 脚本
const pythonProcess = spawn('python', ['script.py']);
// 监听标准输出
pythonProcess.stdout.on('data', (data) => {
console.log(`标准输出:\n${data}`);
});
// 监听标准错误
pythonProcess.stderr.on('data', (data) => {
console.error(`标准错误:\n${data}`);
});
// 监听子进程关闭事件
pythonProcess.on('close', (code) => {
console.log(`子进程退出,退出码 ${code}`);
});
注意:在某些系统中,默认的 python
命令可能指向 Python 2.x 版本。如果需要确保使用 Python 3.x,可以使用 python3
代替 python
:
javascriptconst pythonProcess = spawn('python3', ['script.py']);
python-shell
python-shell
是一个方便的 Node.js 库,用于简化与 Python 脚本的交互。
python-shell
首先,通过 npm 安装 python-shell
:
bashnpm install python-shell
javascriptconst { PythonShell } = require('python-shell');
let options = {
mode: 'text',
pythonPath: 'python3', // 根据需要设置 Python 路径
pythonOptions: ['-u'], // 保持输出流打开
scriptPath: './scripts' // Python 脚本所在目录
};
PythonShell.run('script.py', options, function (err, results) {
if (err) throw err;
console.log('Python 脚本执行结果:');
console.log(results); // results 是一个字符串数组
});
python-shell
允许你在 Node.js 和 Python 脚本之间发送和接收消息,实现双向通信。
Node.js 端:
javascriptconst { PythonShell } = require('python-shell');
let pyshell = new PythonShell('script.py', { scriptPath: './scripts' });
pyshell.send('Hello from Node.js');
pyshell.on('message', function (message) {
console.log('收到来自 Python 的消息:', message);
});
pyshell.end(function (err, code, signal) {
if (err) throw err;
console.log('Python 脚本结束,退出码:', code);
});
Python 端 (script.py
):
pythonimport sys
def main():
# 接收来自 Node.js 的消息
message = sys.stdin.readline().strip()
print(f"收到消息: {message}")
# 发送消息回 Node.js
print("Hello from Python")
if __name__ == "__main__":
main()
注意:为了实现双向通信,Python 脚本需要能够读取标准输入并写入标准输出。
另一种方式是将 Python 脚本作为一个独立的服务运行,通过 HTTP 请求或其他进程间通信(IPC)机制与 Node.js 应用进行交互。
示例:使用 Flask 创建一个简单的 API
python# app.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/process', methods=['POST'])
def process():
data = request.json
# 处理数据
result = {"output": "处理后的数据"}
return jsonify(result)
if __name__ == '__main__':
app.run(port=5000)
javascriptconst axios = require('axios');
async function callPythonService() {
try {
const response = await axios.post('http://localhost:5000/process', {
// 发送的数据
input: '数据'
});
console.log('Python 服务响应:', response.data);
} catch (error) {
console.error('调用 Python 服务出错:', error);
}
}
callPythonService();
领取专属 10元无门槛券
手把手带您无忧上云