- 论坛徽章:
- 0
|
- #!/usr/bin/env python
- #coding:utf-8
- import time
- import sys
- ###
- # 生成器與協程
- ##
- ###
- # 生成器
- # 不斷返回新行
- # @param [in] f 打開的文件描述符
- # @yield line 新的行
- ##
- def tail(f):
- f.seek(0,2) # 移動到文件末尾
- # To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.
- while True:
- line = f.readline() # 嘗試讀取一個新的文本行
- if not line: # 如果沒有內容,暫時休眠并再次嘗試
- time.sleep(0.1)
- continue
- yield line
- ###
- # 協程
- # 查找匹配關鍵字的輸入行
- # @param [in] 要匹配的關鍵字
- # @print [out] 打印匹配的行
- ##
- def print_matches(matchtext):
- print ("Looking for "+matchtext)
- while True:
- line = (yield) # 獲取一個文本
- if matchtext in line:
- print (line)
- if __name__ == "__main__":
- if len(sys.argv) != 2:
- sys.exit(1)
-
- matchers = [ # 一組匹配協程
- print_matches("python"),
- print_matches("www.lkcc.info"),
- print_matches("bbs.lkcc.info")
- ]
-
- for m in matchers: # 通過調用next()準備所有的匹配協程, 執行到第一個yield語句
- m.next()
- f = open(sys.argv[1])
- for line in tail(f):
- for m in matchers:
- m.send(line)
复制代码 执行后说:
求解。。谢谢。。 |
|