开发者

Python readline from pipe on Linux

开发者 https://www.devze.com 2023-03-10 00:56 出处:网络
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 u

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, w开发者_JAVA百科riteEnd = 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()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号