【问题标题】:Only pipe when data arrives仅在数据到达时进行管道传输
【发布时间】:2017-02-24 21:13:54
【问题描述】:

我尝试在 Linux 上学习简单的管道知识:

sender.py:

# sender.py
import random
import sys
import time

while True:
    r = random.randrange(5)
    print(r)
    sys.stdout.flush()
    time.sleep(1)

receiver.py:

# receiver.py
import sys

while True:
    line = sys.stdin.readline()
    print("hello " + line.strip() + " hello")
    sys.stdout.flush()

当我这样做时:

$ python sender.py | python receiver.py

我有如下预期的输出:

hello 3 hello
hello 2 hello
hello 2 hello
hello 0 hello
...
^C

到目前为止,一切正常。有问题的部分如下。当我尝试这样做时:

$ echo "50" | python receiver.py

我期望的输出是:

hello 50 hello

但是,相反,我有以下行无限次出现:

hello  hello

我的问题:

  1. 这是怎么回事? "echo "50" | python receiver.py" 背后的逻辑是什么?
  2. 有没有办法改变我的 receiver.py 使其只打印一次hello 50 hello

【问题讨论】:

    标签: python linux pipe


    【解决方案1】:

    当只提供一个输入时,您正在无限期地读取输入。当没有收到任何内容时,您需要制作您的脚本break

    # receiver.py
    import sys
    
    while True:
        line = sys.stdin.readline()
        if not line:
            break
        print("hello " + line.strip() + " hello")
        sys.stdout.flush()
    

    【讨论】:

      【解决方案2】:

      来自the documentation

      ...如果 f.readline() 返回一个空字符串,则已到达文件末尾...

      将您的代码更改为:

      import sys
      
      while True:
          line = sys.stdin.readline()
          if not len(line):
              break
          print("hello " + line.strip() + " hello")
          sys.stdout.flush()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多