Linux 上的 Python 从管道读取行
当使用 os.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 ?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
os.fdopen()
从文件描述符中获取类文件对象。You can use
os.fdopen()
to get a file-like object from a file descriptor.将管道从
os.pipe()
传递到os.fdopen()
,它应该从文件描述符构建一个文件对象。Pass the pipe from
os.pipe()
toos.fdopen()
, which should build a file object from the filedescriptor.听起来您想获取一个文件描述符(数字)并将其转换为文件对象。
fdopen
函数应该做到这一点:现在无法测试,如果不起作用请告诉我。
It sounds like you want to take a file descriptor (number) and turn it into a file object. The
fdopen
function should do that:Can't test this right now so let me know if it doesn't work.
os.pipe()
返回文件描述符,因此您必须像这样包装它们:有关更多详细信息,请参阅 http://docs.python.org/library/os.html#os.fdopen
os.pipe()
returns file descriptors, so you have to wrap them like this: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.