【问题标题】:console logging the python script console output in node.js控制台在 node.js 中记录 python 脚本控制台输出
【发布时间】:2018-08-15 23:55:12
【问题描述】:

我正在开发 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'?

【问题讨论】:

    标签: javascript python node.js opencv stdout


    【解决方案1】:

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

    print('somestring', flush=True)
    

    在 python 3.3+ 中可以正常刷新

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

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

    【讨论】: