免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3011 | 回复: 3
打印 上一主题 下一主题

协程没有next方法? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-06-02 12:28 |只看该作者 |倒序浏览
  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. import time
  4. import sys
  5. ###
  6. #  生成器與協程
  7. ##
  8. ###
  9. #  生成器
  10. #  不斷返回新行
  11. #  @param [in]  f    打開的文件描述符
  12. #  @yield line 新的行
  13. ##
  14. def tail(f):
  15.         f.seek(0,2)        # 移動到文件末尾
  16.                                 # 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.
  17.         while True:
  18.                 line = f.readline()        # 嘗試讀取一個新的文本行
  19.                 if not line:                # 如果沒有內容,暫時休眠并再次嘗試
  20.                         time.sleep(0.1)
  21.                         continue
  22.                 yield line
  23. ###
  24. #  協程
  25. #  查找匹配關鍵字的輸入行
  26. #  @param [in]  要匹配的關鍵字
  27. #  @print [out] 打印匹配的行
  28. ##
  29. def print_matches(matchtext):
  30.         print ("Looking for "+matchtext)
  31.         while True:
  32.                 line = (yield)        # 獲取一個文本
  33.                 if matchtext in line:
  34.                         print (line)

  35. if __name__ == "__main__":
  36.         if len(sys.argv) != 2:
  37.                 sys.exit(1)
  38.        
  39.         matchers = [ # 一組匹配協程
  40.                 print_matches("python"),
  41.                 print_matches("www.lkcc.info"),
  42.                 print_matches("bbs.lkcc.info")
  43.         ]
  44.        
  45.         for m in matchers:        # 通過調用next()準備所有的匹配協程, 執行到第一個yield語句
  46.                 m.next()

  47.         f = open(sys.argv[1])
  48.         for line in tail(f):
  49.                 for m in matchers:
  50.                         m.send(line)
复制代码
执行后说:

求解。。谢谢。。

论坛徽章:
0
2 [报告]
发表于 2011-06-02 13:26 |只看该作者
回复 1# 小锐同学1
python3里面  next() 被重命名为__next__(),改成m.__next__()试一下。建议你换2.7。

论坛徽章:
0
3 [报告]
发表于 2011-06-02 13:49 |只看该作者
回复 2# 106033177


    谢谢大神。

可以了,不过貌似程序逻辑有错误。

一个这样的文件 ,却没有匹配的行被输出。

我再去找找错误。

论坛徽章:
0
4 [报告]
发表于 2011-06-02 13:51 |只看该作者
搞定了,是我的逻辑错了,昨天的程序,今天来看,懵懵懂懂的。

新手一个,学习中。

感谢大神的帮助。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP