Linux上来自管道的Python readline
使用Linux上来自管道的Python readline,python,pipe,readline,Python,Pipe,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 num
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 您可以使用从文件描述符获取类似文件的对象
import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
firstLine = readFile.readline()
将管道从
os.pipe()
传递到,这将从filedescriptor构建一个文件对象。听起来您想获取一个文件描述符(编号)并将其转换为一个文件对象。该功能应做到:
import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
firstLine = readFile.readline()
import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
# something somewhere writes to the pipe
firstLine = readFile.readline()
现在无法测试此项,因此如果它不起作用,请告诉我。os.pipe()
返回文件描述符,因此您必须像这样包装它们:
readF = os.fdopen(readEnd)
line = readF.readline()
有关更多详细信息,请参见我知道这是一个老问题,但这里有一个不会死锁的版本
import os, threading
def Writer(pipe, data):
pipe.write(data)
pipe.flush()
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
writeFile = os.fdopen(writeEnd, "w")
thread = threading.Thread(target=Writer, args=(writeFile,"one line\n"))
thread.start()
firstLine = readFile.readline()
print firstLine
thread.join()
太好了,我知道它必须很简单!