协程没有next方法?
时间:2011-06-02
来源:互联网
- #!/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)

求解。。谢谢。。
作者: 小锐同学1 发布时间: 2011-06-02
回复 小锐同学1
python3里面 next() 被重命名为__next__(),改成m.__next__()试一下。建议你换2.7。
python3里面 next() 被重命名为__next__(),改成m.__next__()试一下。建议你换2.7。
作者: 106033177 发布时间: 2011-06-02
回复 106033177
谢谢大神。
可以了,不过貌似程序逻辑有错误。
一个这样的文件
,却没有匹配的行被输出。
我再去找找错误。
谢谢大神。
可以了,不过貌似程序逻辑有错误。
一个这样的文件

我再去找找错误。
作者: 小锐同学1 发布时间: 2011-06-02
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28