繁体   English   中英

Python 从 Linux 上的 pipe 读取线

[英]Python readline from pipe on Linux

使用os.pipe()创建 pipe 时,它返回 2 个文件号; 一个读端和一个写端,可以用os.write() / os.read()读写形式; 没有 os.readline()。 可以使用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

简而言之,当您拥有的只是文件句柄号时,是否可以使用 readline ?

您可以使用os.fdopen()从文件描述符中获取类似文件的 object。

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

将 pipe 从os.pipe()传递给os.fdopen() ,这应该从文件描述符构建一个文件 object 。

听起来您想获取文件描述符(数字)并将其转换为文件 object。 fdopen应该这样做:

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

现在无法测试,所以如果它不起作用,请告诉我。

os.pipe()返回文件描述符,所以你必须像这样包装它们:

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

有关详细信息,请参阅http://docs.python.org/library/os.html#os.fdopen

我知道这是一个老问题,但这是一个不会死锁的版本。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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