【问题标题】:ChildProcess: stdin not getting read by Python readlineChildProcess:标准输入没有被 Python readline 读取
【发布时间】:2015-10-15 09:27:40
【问题描述】:

我正在尝试使用child_process 通过标准输入/输出从 Node 与 Python 脚本进行交互,如下所示:

var p = require('child_process').spawn('python', ['test_io.py']);

p.stdout.on('data', function(data) {
  console.log(data.toString());
});

p.stdin.write('thing');

这是相关的 Python 部分:

import io
import sys

_input = io.open(sys.stdin.fileno())
_output = io.open(sys.stdout.fileno(), 'w')

while True:
  _output.write(_input.readline())

但是,现在 Python 脚本似乎没有读取通过 stdin.write 传入的“事物”。这些写入不应该缓冲吗?我在这里做错了什么。

提前致谢。

【问题讨论】:

    标签: python node.js stdout stdin child-process


    【解决方案1】:

    除了@lispHK01 回答您需要终止标准输入 - 特别是在发送少量数据时,因为它将位于缓冲区中。

    试试这个:

    var p = require('child_process').spawn('python', ['test_io.py'], { stdio: 'pipe'});
    
    p.stdin.write('thing');
    p.stdin.end();
    

    【讨论】:

      【解决方案2】:

      试试这个

      var p = require('child_process').spawn('python', ['test_io.py'], { stdio: 'pipe'});
      

      ChildProcess 有一些特质——来自 ChildProcess.stdin 的文档:

      如果孩子不是在 stdio[0] 设置为“管道”的情况下生成的,那么这个 不会被设置。

      https://nodejs.org/api/child_process.html#child_process_child_stdin

      【讨论】:

        猜你喜欢
        • 2015-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-22
        • 1970-01-01
        相关资源
        最近更新 更多