我正在从这张幻灯片中学习Python的生成器:http://www.dabeaz.com/generators/Generators.pdf
其中有一个例子,可以这样描述:
你有一个名为的日志文件log.txt,写一个程序到观看它的内容,如果有新行添加,打印它们.两种解决方案
1. with generator:
import time
def follow(thefile):
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
logfile = open("log.txt")
loglines = follow(logfile)
for line in loglines:
print line
2. Without generator:
import time
logfile = open("log.txt")
while True:
line = logfile.readline()
if not line:
time.sleep(0.1)
continue
print line
Run Code Online (Sandbox Code Playgroud)
在这里使用发电机有什么好处?
如果你拥有的只是锤子,那么一切看起来都像钉子
我几乎只是想用上面的引用来回答这个问题.仅仅因为你并不意味着你需要一直.
但概念上,生成器版本分离功能,跟随功能用于在等待新输入时封装文件的连续读取.这使您可以使用所需的新行释放循环中的任何内容.在第二个版本中,从文件中读取并打印输出的代码与控制循环混合在一起.在这个小例子中,这可能不是真正的问题,但这可能是你想要考虑的事情.