python多任务及返回值的处理方法

yipeiwu_com6年前Python基础

废话不多说,直接上代码!

# coding:utf-8
from multiprocessing import Pool
import time
 
 
def keywords(title, content, top_n=5):
 print u'关键词提取...'
 print title, content, top_n
 time.sleep(3)
 return 0, [u"晴", u"多云"]
 
 
def category(title, content):
 print u'文本分类...'
 print title, content
 time.sleep(5)
 return 1, [u"天气"]
 
 
def run(title, content):
 keywords_list = []
 category_list = []
 pool = Pool(processes=2)
 q = []
 q.append(pool.apply_async(keywords, args=(title, content, 5)))
 q.append(pool.apply_async(category, args=(title, content)))
 for item in q:
  r = item.get()
  if r[0] == 0:
   keywords_list = r[1]
  elif r[0] == 1:
   category_list = r[1]
 pool.close()
 pool.join()
 
 return category_list, keywords_list
 
if __name__ == "__main__":
 title = u"天气预报"
 content = u"北京今日天气:晴转多云"
 t1 = time.time()
 category_list, keywords_list = run(title, content)
 print "分类结果:", " ".join(category_list)
 print "关键词提取结果", " ".join(keywords_list)
 print time.time() - t1

或者:

# coding:utf-8
from multiprocessing import Pool
import time
 
 
def keywords(title, content, top_n=5):
 print u'关键词提取...'
 print title, content, top_n
 time.sleep(3)
 return 0, [u"晴", u"多云"]
 
 
def category(title, content):
 print u'文本分类...'
 print title, content
 time.sleep(5)
 return 1, [u"天气"]
 
 
def run(title, content):
 keywords_list = []
 category_list = []
 pool = Pool(processes=2)
 q = []
 q.append(pool.apply_async(keywords, args=(title, content, 5)))
 keywords_list = [w["word"] for w in q[0].get()[1]]
 category_list = category(title, content)[1]
 pool.close()
 pool.join()
 
 return category_list, keywords_list
 
if __name__ == "__main__":
 title = u"天气预报"
 content = u"北京今日天气:晴转多云"
 t1 = time.time()
 category_list, keywords_list = run(title, content)
 print "分类结果:", " ".join(category_list)
 print "关键词提取结果", " ".join(keywords_list)
 print time.time() - t1

以上这篇python多任务及返回值的处理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python利用装饰器进行运算的实例分析

今天想用python的装饰器做一个运算,代码如下 >>> def mu(x): def _mu(*args,**kwargs): return x*x...

python基础教程之简单入门说明(变量和控制语言使用方法)

简介有兴趣可以看看: 解释性语言+动态类型语言+强类型语言交互模式:(主要拿来试验,可以试试 ipython)复制代码 代码如下:$python>>> print 'h...

python中defaultdict的用法详解

初识defaultdict 之前在使用字典的时候, 用的比较随意, 只是简单的使用dict. 然而这样在使用不存在的key的时候发生KeyError这样的一个报错, 这时候就该defa...

用Python生成器实现微线程编程的教程

微线程领域(至少在 Python 中)一直都是 Stackless Python 才能涉及的特殊增强部分。关于 Stackless 的话题以及最近它经历的变化,可能本身就值得开辟一个专栏...

python单元测试unittest实例详解

本文实例讲述了python单元测试unittest用法。分享给大家供大家参考。具体分析如下: 单元测试作为任何语言的开发者都应该是必要的,因为时隔数月后再回来调试自己的复杂程序时,其实也...