我從這張幻燈片學習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
什麼用發電機這裏有什麼好處?
在Python 2.6及更高版本中,最好調用'next(gen)'而不是'gen.next()'。在Python 3.x中,後一種語法不再可用。 – 2011-05-28 14:32:57
儘管我同意你幾乎總是希望使用'for'來迭代文件的行,而不是調用'readline',這是少數情況下你不知道的情況之一。 'for'循環會在第一次到達文件結尾時結束,它不會像調用readline()那樣給你重複的空字符串。 – Duncan 2011-05-28 14:36:48