首页 > 解决方案 > 如果太长,通过 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());
    }
  });

标签: pythonnode.jsstdoutchild-process

解决方案


发出的数据是分块的,所以如果你想解析 aJSON你需要加入所有的块,并在endperform上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);
    }
});

推荐阅读