本文實例講述了python協程用法。分享給大家供大家參考。具體如下:
把函數編寫為一個任務,從而能處理發送給他的一系列輸入,這種函數稱為協程
def print_matchs(matchtext): print "looking for",matchtext while True: line = (yield) #用 yield語句并以表達式(yield)的形式創建協程 if matchtext in line: print line>>> matcher = print_matchs('python')>>> matcher.next()looking for python>>> matcher.send('hello python')#看生成器那片,關于send()跟next()的區別hello python>>> matcher.send('test')>>> matcher.send('python is cool')python is cool>>>matcher.close()
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答