python - 通过 child_process 从 Python 向 Node 发送 JSON 如果太长会被截断,如何修复?

标签 python node.js stdout child-process

我的 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/

相关文章:

python - 连接(合并)pandas 中的两个系列

python - 获取 twitter 流 api 时如何在 Tornado 中重启 ioloop?

Javascript lodash 展平分层对象

html - 如何从视频中间制作视频缩略图?

python - 在 Python 字符串中同时包含单引号和双引号

Python NLTK : parse string using conjoint structure, 进入无限递归

javascript - 是否可以将参数拆分为 NodeJS 中的值?

与子进程的标准输入/标准输出异步通信

c - STDOUT 上的 setvbuf 对其他进程安全吗?

batch-file - 从批处理文件内重定向 stdout 和 stderr