tMC
tMC

Reputation: 19355

Python readline from pipe on Linux

When creating a pipe with os.pipe() it returns 2 file numbers; a read end and a write end which can be written to and read form with os.write()/os.read(); there is no os.readline(). Is it possible to 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 the file handle number?

Upvotes: 6

Views: 11355

Answers (5)

Keeely
Keeely

Reputation: 1015

I know this is an old question, but here is a version that doesn't deadlock.

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()

Upvotes: 1

bradley.ayers
bradley.ayers

Reputation: 38392

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()

Upvotes: 14

Zaur Nasibov
Zaur Nasibov

Reputation: 22679

os.pipe() returns file descriptors, so you have to wrap them like this:

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

For more details see http://docs.python.org/library/os.html#os.fdopen

Upvotes: 4

Brendan Long
Brendan Long

Reputation: 54312

It sounds like you want to take a file descriptor (number) and turn it into a file object. The fdopen function should do that:

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

Can't test this right now so let me know if it doesn't work.

Upvotes: 4

sarnold
sarnold

Reputation: 104110

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

Upvotes: 4

Related Questions