Linux上管道的Python readline


问题内容

os.pipe()它创建管道时,将返回2个文件编号;可以用os.write()/写入和读取形式的读取端和写入端os.read();没有os.readline()。是否可以使用readline?

import os
readEnd, writeEnd = os.pipe()
# something somewhere writes to the pipe
firstLine = readEnd.readline() #doesn't work; os.pipe returns just fd numbers

简而言之,当您仅拥有文件句柄编号时,是否可以使用readline?


问题答案:

您可以os.fdopen()用来从文件描述符中获取类似文件的对象。

import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
firstLine = readFile.readline()