通过在同一个对象中实现上下文协议和迭代器协议,你可以写出这样漂亮的代码:
with cat("/etc/passwd") as lines:
for line in lines:
if "mail" in line:
print line.strip()
break
这是一个示例实现,在 Linux 机器上使用 Python 2.5 进行了测试。它读取 的行,/etc/passwd
直到找到 user的行audio
,然后停止:
from __future__ import with_statement
class cat(object):
def __init__(self, fname):
self.fname = fname
def __enter__(self):
print "[Opening file %s]" % (self.fname,)
self.file_obj = open(self.fname, "rt")
return self
def __exit__(self, *exc_info):
print "[Closing file %s]" % (self.fname,)
self.file_obj.close()
def __iter__(self):
return self
def next(self):
line = self.file_obj.next().strip()
print "[Read: %s]" % (line,)
return line
def main():
with cat("/etc/passwd") as lines:
for line in lines:
if "mail" in line:
print line.strip()
break
if __name__ == "__main__":
import sys
sys.exit(main())
或者更简单:
with open("/etc/passwd", "rt") as f:
for line in f:
if "mail" in line:
break
文件对象实现迭代器协议(参见http://docs.python.org/library/stdtypes.html#file-objects)