我的 Node 和 Python 后端运行得很好,但我现在遇到了一个问题,如果我从 Python 返回的 Node 发送的 JSON 太长,它会被分成两部分,并且 Node 端的 JSON.parse 会失败。
我应该如何解决这个问题?例如,第一批剪辑位于
... [1137.6962355826706, -100.78015825640887], [773.3834338399517, -198
第二个包含剩余的几个条目
.201506231888], [-87276.575065248, -60597.8827676457], [793.1850250453127,
-192.1674702207991], [1139.4465453979683, -100.56741252031816],
[780.498416769341, -196.04064849430705]]}
我是否必须在 Node 端为长 JSON 创建一些逻辑,或者这是我在 Python 端遇到的某种缓冲问题,我可以通过正确的设置来克服?这是我在 python 方面所做的一切:
outPoints, _ = cv2.projectPoints(inPoints, np.asarray(rvec),
np.asarray(tvec), np.asarray(camera_matrix), np.asarray(dist_coeffs))
# flatten the output to get rid of double brackets per result before JSONifying
flattened = [val for sublist in outPoints for val in sublist]
print(json.dumps({'testdata':np.asarray(flattened).tolist()}))
sys.stdout.flush()
在 Node 端:
// Handle python data from print() function
pythonProcess.stdout.on('data', function (data){
try {
// If JSON handle the data
console.log(JSON.parse(data.toString()));
} catch (e) {
// Otherwise treat as a log entry
console.log(data.toString());
}
});
最佳答案
发出的数据是分块的,因此如果您想解析 JSON
,您需要连接所有 block ,并在 end
执行 JSON.parse
。
By default, pipes for stdin, stdout, and stderr are established between the parent Node.js process and the spawned child. These pipes have limited (and platform-specific) capacity. If the child process writes to stdout in excess of that limit without the output being captured, the child process will block waiting for the pipe buffer to accept more data.
在 linux每个 block 限制为 65536
字节。
In Linux versions before 2.6.11, the capacity of a pipe was the same as the system page size (e.g., 4096 bytes on i386). Since Linux 2.6.11, the pipe capacity is 65536 bytes.
let result = '';
pythonProcess.stdout.on('data', data => {
result += data.toString();
// Or Buffer.concat if you prefer.
});
pythonProcess.stdout.on('end', () => {
try {
// If JSON handle the data
console.log(JSON.parse(result));
} catch (e) {
// Otherwise treat as a log entry
console.log(result);
}
});
关于python - 通过 child_process 从 Python 向 Node 发送 JSON 如果太长会被截断,如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50787082/