Python readline from pipe on Linux

When creating a channel with, os.pipe()it returns 2 file numbers; the end of reading and the end of the record, which can be written into the form and read with os.write()/ os.read(); no os.readline (). Can I use 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

In short, is it possible to use readline when all you have is a file descriptor number?

+5
source share
5 answers

You can use os.fdopen()to get a file-like object from a file descriptor.

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

Pass the handset from os.pipe()to os.fdopen(), which should create a file object from the filedescriptor file.

+4

It looks like you want to take a file descriptor (number) and turn it into an object file. The function fdopenshould do this:

import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
# something somewhere writes to the pipe
firstLine = readFile.readline()

I canโ€™t check it right now, so let me know if this doesnโ€™t work.

+4
source

os.pipe() returns file descriptors, so you need to wrap them as follows:

readF = os.fdopen(readEnd)
line = readF.readline()

See http://docs.python.org/library/os.html#os.fdopen for more details.

+4
source

I know this is an old question, but here is a version that has not come to a standstill.

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()
+1
source

All Articles