在Linux上从管道中读取Python输入
当你使用 os.pipe()
创建一个管道时,它会返回两个文件编号:一个是读端,另一个是写端。你可以用 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 呢?
5 个回答
4
把从 os.pipe()
得到的管道传给 os.fdopen()
,这个函数会根据文件描述符创建一个文件对象。
4
听起来你想把一个文件描述符(就是一个数字)变成一个文件对象。可以使用 fdopen
这个函数来实现:
import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
# something somewhere writes to the pipe
firstLine = readFile.readline()
我现在没法测试这个,所以如果它不管用的话,告诉我一声。
13
你可以使用 os.fdopen()
这个函数,从一个文件描述符获取一个像文件一样的对象。
import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
firstLine = readFile.readline()