简体   繁体   中英

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?

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

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM