python - 如果太长,通过 child_process 从 Python 向 Node 发送 JSON 会被截断,如何解决?
问题描述
我的 Node 和 Python 后端运行得很好,但是我现在遇到了一个问题,如果我从 Python 发回的 JSON 没有 Node 太长,它会分成两部分,并且我在 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()
在节点方面:
// 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());
}
});
解决方案
发出的数据是分块的,所以如果你想解析 aJSON
你需要加入所有的块,并在end
perform上JSON.parse
。
默认情况下,stdin、stdout 和 stderr 的管道在父 Node.js 进程和衍生的子进程之间建立。这些管道的容量有限(且特定于平台)。如果子进程写入标准输出超出该限制而没有捕获输出,则子进程将阻塞等待管道缓冲区接受更多数据。
在linux中,每个块仅限于65536
字节。
在 2.6.11 之前的 Linux 版本中,管道的容量与系统页面大小相同(例如,在 i386 上为 4096 字节)。从 Linux 2.6.11 开始,管道容量为 65536 字节。
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);
}
});
推荐阅读
- typescript - vscode.workspace.workspaceFolders 返回错误。Vscode 扩展
- c# - 将插入字符串构建到 sql 时遇到 CSV/Json 的问题
- r - Nanair 包裹没有预期的结果
- c++ - 类中的虚拟布尔函数参数不起作用
- java - 在while循环中声明字符串变量,而不是整个循环 - java
- java - 在 Android 中使用 TextUtil 类优于 String 类有什么优势吗?
- python - Flask url_for 返回404(文件未找到),但绝对路径正确
- flutter - 颤振检查器不适用于我的 github 存储库中的应用程序
- python-3.x - 将列中的值与整数进行比较
- java - 使用 ArrayList 的挂钩方法
范围