JavaScript代码示例
const { spawn } = require('child_process');
// 创建子进程,假设Python脚本名为square.py
const pythonProcess = spawn('python', ['square.py']);
// 向子进程发送数据
const numberToSend = 5;
pythonProcess.stdin.write(numberToSend.toString() + '\n');
pythonProcess.stdin.end();
// 获取子进程输出结果
let result = '';
pythonProcess.stdout.on('data', (data) => {
result += data.toString();
});
pythonProcess.on('close', () => {
console.log(`子进程计算结果: ${result}`);
});
Python脚本示例(square.py)
import sys
try:
number = float(sys.stdin.readline().strip())
square_result = number ** 2
print(square_result)
except ValueError:
print('输入错误')
缓冲区溢出问题及解决方案
- 问题:如果子进程产生的数据量非常大,超过了Node.js默认设置的缓冲区大小,可能会导致数据丢失或程序崩溃。
- 解决方案:
- 增加缓冲区大小:在
spawn
时可以设置maxBuffer
参数,例如const pythonProcess = spawn('python', ['square.py'], { maxBuffer: 1024 * 1024 });
,这里将缓冲区大小设置为1MB。
- 分段处理:在子进程中,如果输出数据较大,可以考虑分段输出,在Node.js父进程中分段接收并处理。例如,Python脚本中可以按固定长度分块输出数据,Node.js父进程通过多次接收
stdout
事件的数据来处理完整数据。