【问题标题】:Getting readline to block on a FIFO让 readline 在 FIFO 上阻塞
【发布时间】:2010-03-09 03:01:32
【问题描述】:

我创建了一个先进先出:

mkfifo tofetch

我运行这个 python 代码:

fetchlistfile = file("tofetch", "r")
while 1:
    nextfetch = fetchlistfile.readline()
    print nextfetch

正如我所希望的,它在 readline 上停滞不前。我跑:

echo "test" > tofetch

我的程序不再停止。它读取该行,然后继续永远循环。没有新数据为什么不会再次停顿?

我也尝试查看“not fetchlistfile.closed”,我不介意在每次写入后重新打开它,但 Python 认为 fifo 仍然打开。

【问题讨论】:

    标签: python pipe fifo


    【解决方案1】:

    根据readline 的文档,当且仅当您位于文件末尾时,它才会返回空字符串。已关闭与文件结尾不同。文件对象只会在您调用 .close() 时关闭。当您的代码到达文件末尾时,readline() 会不断返回空字符串。

    如果你只是将文件对象用作迭代器,Python 将自动一次读取一行并在文件末尾停止。像这样:

    fetchlistfile = file("tofetch", "r")
    for nextfetch in fetchlistfile:
        print nextfetch
    

    echo "test" > tofetch 命令打开命名管道,将“test”写入其中,然后关闭它的管道末端。因为管道的写端是关闭的,所以读端看到的是文件尾。

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 2013-08-10
      • 2017-10-05
      • 1970-01-01
      • 2017-07-09
      • 2017-04-26
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      相关资源
      最近更新 更多