python协程用法实例分析

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

OpenCV+python手势识别框架和实例讲解

OpenCV+python手势识别框架和实例讲解

基于OpenCV2.4.8和 python 2.7实现简单的手势识别。 以下为基本步骤 1.去除背景,提取手的轮廓 2. RGB->YUV,同时计算直方图 3.进行形态学滤波,提...

Django 在iframe里跳转顶层url的例子

描述 A网页为一个专门设计的登录页面login.html,通过iframe嵌套在B页面中index.html,登录后会进入后台C页面consule.html.问题来了,登录成功后,通过D...

python线程池的实现实例

直接上代码:复制代码 代码如下:# -*- coding: utf-8 -*- import Queue import threadingimport urllibimport urll...

Python基础之循环语句用法示例【for、while循环】

本文实例讲述了Python基础之循环语句用法。分享给大家供大家参考,具体如下: while 循环 Python中while语句的一般形式: while 判断条件:  &nbs...

Python代码解决RenderView窗口not found问题

Python代码解决RenderView窗口not found问题

源起   Error:setParent: Object 'renderView' not found   这是一个在工作中很常见的问题,以前做特效的时候有10%的概率会碰到,多发生在打...