我创建了一个fifo:
mkfifo tofetch
Run Code Online (Sandbox Code Playgroud)
我运行这个python代码:
fetchlistfile = file("tofetch", "r")
while 1:
nextfetch = fetchlistfile.readline()
print nextfetch
Run Code Online (Sandbox Code Playgroud)
正如我所希望的那样,它在readline上停滞不前.我跑:
echo "test" > tofetch
Run Code Online (Sandbox Code Playgroud)
我的程序不再失速了.它读取该行,然后继续循环.当没有新数据时,为什么它不会再次失速?
我也试过看"不是fetchlistfile.closed",我不介意在每次写入后重新打开它,但Python认为fifo仍然是开放的.
根据readline的文档,当且仅当您位于文件末尾时,它才会返回空字符串。关闭与文件结束不同。仅当调用 .close() 时,文件对象才会关闭。当代码到达文件末尾时,readline() 不断返回空字符串。
如果你只使用文件对象作为迭代器,Python 将自动一次读取一行并在文件末尾停止。像这样:
fetchlistfile = file("tofetch", "r")
for nextfetch in fetchlistfile:
print nextfetch
Run Code Online (Sandbox Code Playgroud)
该echo "test" > tofetch命令打开命名管道,向其中写入“test”,然后关闭管道的末端。因为管道的写入端是关闭的,所以读取端看到的是文件结尾。