微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从Linux上的管道读取Python readline

如何解决从Linux上的管道读取Python readline

| 当创建带有“ 0”的管道时,它将返回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()
从文件描述符中获取类似文件的对象。
import os
readEnd,writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
firstLine = readFile.readline()
    ,        将管道从
os.pipe()
传递到
os.fdopen()
,这应从filedescriptor建立文件对象。     ,        听起来您想要一个文件描述符(数字)并将其变成文件对象。
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()
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。