gpt4 book ai didi

python - readline 真的不会像在空的类文件对象上那样在空文件上阻塞吗?

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:03 24 4
gpt4 key购买 nike

这是我用来试验 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() block 会更加统一,就像处理类文件对象一样。

最佳答案

文件对象不知道其他人是否有该文件的打开句柄,因此它们无法区分“有写入器的空文件”和“没有写入器的空文件”;关闭文件的写入者对于读取该文件的句柄来说是不可见的。

相比之下,管道传达此类信息,它们是由编写者显式关闭以将数据传达给读者的流。

如果文件的行为就像管道一样,由于缺乏有关编写者的信息,当您用完行时,您将无限期地阻塞,等待另一行永远不会到达。

基本上,它们的目的完全不同,不要期望其中一个的行为与另一个完全相同。

关于python - readline 真的不会像在空的类文件对象上那样在空文件上阻塞吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42452618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com