控制台在 node.js 中记录 python 脚本控制台输出

console logging the python script console output in node.js

我正在开发 opencv python 和 node.js 服务器,其中 python 脚本打印出对我的节点服务器有用的字符串 "moved"

我正在使用 'python-shell' 生成 python 脚本作为子进程 但问题是我正在 opencv 中处理视频文件,只有在 cv2.imshow(video window) 退出后节点才会记录控制台日志。我希望它能够实时从 python 脚本在节点中记录输出。

我也没有在条件语句中得到参数(消息 === 'moved')

server.js

var express = require('express');
var app = express();

var PythonShell = require('python-shell');
var pyshell = new PythonShell(__dirname + './script.py');

pyshell.on('message', function (message) {
  // received a message sent from the Python file script.py (returns "moved" string)
  console.log(message);
  console.log(message + 'hi');
  if(true){
    console.log('hey')
  }
  if(message === 'moved'){
    console.log('hit')
  }
});

控制台在 Node.js

moved
hived
hey

还有为什么 'moved' 和 'hi' 连接到 'hived'?

可以通过刷新 python 脚本中的标准输出来完成实时记录

print('somestring', flush=True)

在 python 3.3+

中冲洗效果很好

字符串连接重叠是因为返回的字符串中有'\r' 我用

删除了 '\r' 变量
variable.replace(/\n|\r/g, "")