5

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?

tMC
  • 18,105
  • 14
  • 62
  • 98

5 Answers5

12

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()
dbr
  • 165,801
  • 69
  • 278
  • 343
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
4

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

sarnold
  • 102,305
  • 22
  • 181
  • 238
4

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.

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
4

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

Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
1

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()
Keeely
  • 895
  • 9
  • 21