【问题标题】:Bidrectional node/python communication双向节点/python通信
【发布时间】:2015-03-07 16:47:48
【问题描述】:

我正在尝试在节点和衍生的 Python 进程之间实现简单的双向通信。

Python:

import sys
for l in sys.stdin:
    print "got: %s" % l

节点:

var spawn = require('child_process').spawn;

var child = spawn('python', ['-u', 'ipc.py']);
child.stdout.on('data', function(data){console.log("stdout: " + data)});

var i = 0;
setInterval(function(){
    console.log(i);
    child.stdin.write("i = " + i++ + "\n");
}, 1000);

在 Python 上使用 -u 会强制无缓冲 I/O,因此我希望看到输出(我也尝试过 sys.stdout.flush())但没有。我知道我可以使用child.stdout.end(),但这会阻止我以后写入数据。

【问题讨论】:

    标签: python node.js ipc


    【解决方案1】:

    您的 Python 代码在一行中出现 TypeError: not all arguments converted during string formatting 崩溃

    print "got: " % l
    

    你应该写

    print "got: %s" % l
    

    您可以通过以下操作查看 Python 输出的错误:

    var child = spawn('python', ['-u', 'ipc.py'],
        { stdio: [ 'pipe', 'pipe', 2 ] });
    

    在 Node.js 上,即仅通过管道传输标准输出,但让标准错误进入 Node 的 stderr。


    即使有这些修复,甚至考虑到-usys.stdin.__iter__ will be buffered。要解决此问题,请改用.readline

    for line in iter(sys.stdin.readline, ''):
        print "got: %s" % line
        sys.stdout.flush()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 2021-04-16
      相关资源
      最近更新 更多