python协程用法实例分析

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python实现删除当前目录下除当前脚本以外的文件和文件夹实例

本文实例讲述了Python实现删除当前目录下除当前脚本以外的文件和文件夹。分享给大家供大家参考。具体如下: import os,sys import shutil cur_file...

详解python之协程gevent模块

Gevent官网文档地址:http://www.gevent.org/contents.html 进程、线程、协程区分 我们通常所说的协程Coroutine其实是corporate ro...

Python3多线程操作简单示例

本文实例讲述了Python3多线程操作。分享给大家供大家参考,具体如下: python3 线程中常用的两个模块为: _thread threading(推荐使用) thread 模块已被...

python实现两个文件合并功能

python实现两个文件合并功能

本文将会分析一个文件合并的程序,并指出在合并文件过程中需要注意的问题。 下面是需要合并的文件示例: 分析思路: 要将两个文件合并,首先要将文件读到内存中,成为列表。再将列表...

Python3实现获取图片文字里中文的方法分析

本文实例讲述了Python3实现获取图片文字里中文的方法。分享给大家供大家参考,具体如下: 一、运行环境 (1) win10 (2) pycharm (3) python 3.5 (4)...