那是故意的行为。查看this answer中类似的问题和FIFO行为的概述。与您的问题相关的部分是:When there are no more writers (...) readers are notified about that through read() returning the EOF.
file.readline()docs表示''(空字符串)表示{}已到达:if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.
就这样。在无限循环中,每次尝试读取时都会得到一个空字符串,表示没有更多的写入程序连接。在
没有什么可以阻止您使用命名管道来解决您的任务。最简单的方法就是在没有作家的情况下睡一段时间。以下是工作示例:# server.py
import os
import time
pipe_name = 'pipe_test'
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
with open(pipe_name, 'r') as pipe:
print("Listening for actions...")
while True:
action = pipe.readline()[:-1]
if action == '':
print("No clients. Sleeping...")
time.sleep(1)
else:
print("Action received:", repr(action))
^{pr2}$
注意事项:使用os.open(),这是一个低级函数。可以使用open()与命名管道交互。在
打开命名管道以读取blocks,直到连接第一个写入程序。所以在第一个客户机连接到管道之前,您不会在输出中看到Listening for actions...。作家没有读者也一样。在
您询问“哪个块并处理此字符串,然后在循环中等待另一个字符串”。除非下一个线程不处理当前的字符串,否则它不会被处理。在