readline 真的不会像在类似空文件的对象上那样阻塞在空文件上吗?
Is it really that readline does not block on an empty file as it does on an empty file-like object?
这是我用来试验的代码 Python readline()
。
import threading, os, time
def worker():
file.seek(0)
print ("First attempt on file: " + file.readline().strip())
print ("First attempt on pipe: " + Iget.readline().strip())
print ("Second attempt on pipe: " + Iget.readline().strip())
file.seek(0)
print ("Second attempt on file: " + file.readline().strip())
print ("Third attempt on file: " + file.readline().strip())
fdIget, fdIset = os.pipe()
Iget = os.fdopen(fdIget)
Iset = os.fdopen(fdIset, 'w')
file = open("Test.txt", "w+")
t = threading.Thread(target=worker)
t.start()
time.sleep(2)
Iset.write("Parent pipe\n")
Iset.flush()
file.write("Parent file.\n")
file.flush()
time.sleep(2)
Iset.write("Again Parent pipe\n")
Iset.flush()
file.write("Again Parent file.\n")
file.flush()
t.join()
输出为
First attempt on file:
First attempt on pipe: Parent pipe
Second attempt on pipe: Again Parent pipe
Second attempt on file: Parent file.
Third attempt on file: Again Parent file.
似乎 readline()
不会阻塞空文件 - 也许它看到 EOF 因为文件是空的。另一方面,readline()
阻塞在一个空的类文件对象上——在我们关闭类文件对象之前看不到 EOF。我希望我弄错了——我错过了一些基本的东西。在句柄关闭之前,在空文件上放置 readline()
块会更加统一,就像处理类似文件的对象一样。
文件对象不知道其他人是否有打开的文件句柄,因此它们无法区分 "empty file with writers" 和 "empty file without writers";关闭文件的编写器对读取文件的句柄不可见。
相比之下,管道传递那种信息,它们是被编写器明确关闭以将数据传递给 reader 的流。
如果文件像管道一样,由于缺乏关于作者的信息,当您 运行 出线时,您会无限期地阻塞,等待永远不会到达的另一行。
基本上,它们的用途完全不同,不要指望其中一个的行为与另一个完全相同。
这是我用来试验的代码 Python readline()
。
import threading, os, time
def worker():
file.seek(0)
print ("First attempt on file: " + file.readline().strip())
print ("First attempt on pipe: " + Iget.readline().strip())
print ("Second attempt on pipe: " + Iget.readline().strip())
file.seek(0)
print ("Second attempt on file: " + file.readline().strip())
print ("Third attempt on file: " + file.readline().strip())
fdIget, fdIset = os.pipe()
Iget = os.fdopen(fdIget)
Iset = os.fdopen(fdIset, 'w')
file = open("Test.txt", "w+")
t = threading.Thread(target=worker)
t.start()
time.sleep(2)
Iset.write("Parent pipe\n")
Iset.flush()
file.write("Parent file.\n")
file.flush()
time.sleep(2)
Iset.write("Again Parent pipe\n")
Iset.flush()
file.write("Again Parent file.\n")
file.flush()
t.join()
输出为
First attempt on file:
First attempt on pipe: Parent pipe
Second attempt on pipe: Again Parent pipe
Second attempt on file: Parent file.
Third attempt on file: Again Parent file.
似乎 readline()
不会阻塞空文件 - 也许它看到 EOF 因为文件是空的。另一方面,readline()
阻塞在一个空的类文件对象上——在我们关闭类文件对象之前看不到 EOF。我希望我弄错了——我错过了一些基本的东西。在句柄关闭之前,在空文件上放置 readline()
块会更加统一,就像处理类似文件的对象一样。
文件对象不知道其他人是否有打开的文件句柄,因此它们无法区分 "empty file with writers" 和 "empty file without writers";关闭文件的编写器对读取文件的句柄不可见。
相比之下,管道传递那种信息,它们是被编写器明确关闭以将数据传递给 reader 的流。
如果文件像管道一样,由于缺乏关于作者的信息,当您 运行 出线时,您会无限期地阻塞,等待永远不会到达的另一行。
基本上,它们的用途完全不同,不要指望其中一个的行为与另一个完全相同。