【问题标题】:bash/python stop reading from fifobash/python 停止从 fifo 读取
【发布时间】:2017-10-09 13:17:07
【问题描述】:

我正在尝试获取一个简短的 python 脚本以从 bash/linux 下的 fifo 读取,然后在收到某个单词时停止。我已经完成了以下操作

在 main.py 中

import "sys"
while True:
    line = sys.stdin.readline().rstrip()
    sys.stdout.write(line + " read\n")
    if line=="STOP":
        break
sys.stdout.write("finished\n")

我正在运行这样的脚本:

mkfifo myfifo 
tail -f myfifo | python main.py

在另一个 shell 窗口中我输入:

echo "foobar" > myfifo # "myfifo read" echoed in the other window
echo "STOP" > myfifo # "finished" echoed in other window

但是,另一个窗口中的进程不会停止,而是保持打开状态,直到我向 myfifo 回显其他内容。

有谁知道这里发生了什么以及如何让 python 进程退出?

--- 编辑---

我刚刚将 main.py 重写为 bash 脚本,它也有同样的问题。这似乎是我不熟悉的 tail -f 行为

--- 另一个编辑 ---

如果我在输入“STOP”后搜索 python 进程,我再也找不到它了。这意味着python进程正在完成。问题似乎是tail -f和bash之间的一些交互。

---可能是最终编辑---

好的,我想我已经弄清楚发生了什么,它与 python 无关。

当您将某些内容回显到命名管道时,EOF 会添加到末尾。 tail -fEOF 转换为EOL。这意味着如果我不使用tail -f 而是使用cat 将命名管道的内容通过管道传输到python 脚本的stdin,python 将在阅读@987654332 后失去与stdin 的连接@ 在第一行的末尾。从那时起,尝试从stdin 读取将导致EOF。出于这个原因,python 脚本将显示read\n 的无限列表。如果在使用tail -f 时python 脚本退出,tail -f 在我向命名管道添加其他内容之前不知道这一点。

【问题讨论】:

    标签: bash fifo


    【解决方案1】:

    tail -f 使管道无限期地打开,所以你应该在读完它后调用sys.stdin.close()

    import sys
    
    while True:
        line = sys.stdin.readline().rstrip()
        sys.stdout.write(line + " read\n")
        if line == "STOP":
            break
    
    sys.stdin.close()
    sys.stdout.write("finished\n")
    

    题外话了,不过我也把你的import "sys"改成了import sys

    【讨论】:

      【解决方案2】:

      这是尾巴。

      ./tst.py<myfifo &
      

      然后将您想要的任何内容发送到管道中。代码正在运行(尽管我不得不为我的 python 版本去掉 sys 的引号。)你的问题是 tail 仍然在 -f follow 模式下运行。

      【讨论】:

      • 这样做的问题是,如果我随后将某些内容回显到 myfifo,python 脚本将输出“read\n”的无限列表。我不知道为什么。
      • 编辑您的原始帖子以准确显示您的设置和执行方式。除了 fifo 之外,不要使用尾部或管道。 Keep 尽可能简单和最小化。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2015-11-27
      相关资源
      最近更新 更多