python多线程返回值的实现与处理
题目:
# 编写一个python程序,创建两个子线程,分别到下面的网址获取文本内容
# http://mirrors.163.com/centos/6/isos/x86_64/README.txt
# http://mirrors.163.com/centos/7/isos/x86_64/0_README.txt
# 主线程等待这个两个子线程获取到信息后,将其内容依次合并后存入名为 readme89.TXT 的文件中
答案1:通过返回值实现
1、创建线程类,重构线程基类初始化函数
from threading import Thread # 创建一个线程类
class MyThread(Thread):
# 重定义初始化
def __init__(self,func,args=()):
super(MyThread, self).__init__()
self.func = func
self.args = args # 运行函数(线程)
def run(self):
self.rusult = self.func(*self.args)
# 获得返回值
def get_result(self):
Thread.join(self) # 等待线程执行完毕
try:
return self.rusult
except Exception:
return None
2、创建子线程实现调用返回值的操作
import requests,traceback
from pythondevelop.case_1109ReturnValue import MyThread # 创建两个子线程用于获取网页内容
def thread1():
r = requests.get('http://mirrors.163.com/centos/6/isos/x86_64/README.txt') return r def thread2():
r = requests.get('http://mirrors.163.com/centos/6/isos/x86_64/0_README.txt') return r # 主程序等待子线程获取后合并内容到readme89.TXT
try:
th1= MyThread(thread1)
th2= MyThread(thread2)
th1.start()
th2.start()
th1result = th1.get_result()
th2result = th2.get_result()
if th1result != None and th2result != None and th1result.status_code == 200 and th2result.status_code == :
with open('readme89.txt','w+') as f:
f.write(th1result.text)
f.write('---------------------------------------this is line!!-------------------------------------')
f.write(th2result.text)
f.close()
except:
print(traceback.format_exc()) 答案2:通过将返回值放在预先定义的列表中,及对线程锁的应用
# coding=utf8
import requests,threading urls = [
'http://mirrors.163.com/centos/6/isos/x86_64/README.txt',
'http://mirrors.163.com/centos/6/isos/x86_64/0_README.txt'] # 对应urls 依次存储网页文件内容, 先创建同样个数的元素占位
fileContentList = [None for one in urls] # 锁对象,用来控制访问 fileContentList
lock = threading.Lock() def thread_entry(idx,url):
print('thread #%s start' % idx)
r = requests.get(url) # 注意上面的代码不应该放在获取锁的代码中
lock.acquire()
# 注意 r.text的类型是unicode,可以在文档中查到
fileContentList[idx] = r.text
lock.release() print('thread #%s end' % idx) if __name__ == '__main__':
print('main thread start.') threadpool = [] for idx,url in enumerate(urls): # enumerate()用于遍历数据对象(如列表)组合为一个索引序列,同时列出下标和数据
t = threading.Thread(target=thread_entry,args=(idx,url))
t.start() threadpool.append(t) # 等所有 线程结束
for t in threadpool:
t.join() # 所有线程结束后,所有内容都获取到了,合并内容 mergeTxt = '\n\n----------------------\n\n'.join(fileContentList)
print(mergeTxt) with open('readme89.txt','w',encoding='utf8') as f:
f.write(mergeTxt) print('main thread end.')
python多线程返回值的实现与处理的更多相关文章
- shell如何向python传递参数,shell如何接受python的返回值
1.shell如何向python传递参数 shell脚本 python $sendmailCommandPath $optDate python脚本 lastDateFormat = sys.argv ...
- python函数返回值
2016-08-09 15:01:38 python函数返回值使用return语句,可以返回任意类型的数.如果return语句执行,它之后的所有语句都不再执行. def func(x,y): pri ...
- JAVA多线程解惑之多线程返回值
如果有人问题你,多线程可以有返回值吗?你怎么回答? 看下面例子,我定义了一个类实现了Callable 接口 public class MyCallable implements Callable< ...
- Python 函数返回值
本章详细介绍 返回值: 0x 00 返回值简介 0x 01 指定返回值与隐含返回值 0x 02 return 语句位置与多条 return 语句 0x 03 返回值类型 0x 04 函数嵌套 0x 0 ...
- Python丢弃返回值
函数多个返回值 python的函数支持返回多个值.返回多个值时,默认以tuple的方式返回. 例如,下面两个函数的定义是完全等价的. def f(): return 1,2 def f(): retu ...
- python 函数返回值笔记
今天学习python时候学习到闭包和柯里化 感觉看概念时候不好理解,自己写下大概就明白点了 柯里化如下 定义一个加法函数 def add(x, y): return x + y 这是没有柯里化之前的函 ...
- python的返回值
1.返回值的作用 函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值.函数返回的值被称为返回值.在函数中,可使用return语句将值返回到调用函数的代码行.返回值让你能够将程序的大 ...
- Python 函数返回值、作用域
函数返回值 多条return语句: def guess(x): if x > 3: return "> 3" else: return "<= 3&qu ...
- day09 python函数 返回值 参数
day09 python 一.函数 1.函数 函数是对功能的封装 语法: 定义函数: def 函数名(形参): ...
随机推荐
- 【python基础语法】第6天作业练习题
''' 二.作业(每一道题封装成一个函数) 1.输出99乘法表,结果如下:(提示嵌套for循环,格式化输出) 2.有1 2 3 4 这四个数字,设计程序计算能组成多少个互不相同且无重复数字的3位数?分 ...
- docker搭建环境积累
weblogic12搭建 sudo docker pull ismaleiva90/weblogic12 sudo docker run -d -p : -p : ismaleiva90/weblog ...
- Quartz学习——Quartz大致介绍 转
转自阿飞先生 http://blog.csdn.net/u010648555/article/details/54863144 1. 介绍 Quartz是OpenSymphony开源组织在Job sc ...
- Truck History POJ - 1789 板子题
#include<iostream> #include<cstring> #include<algorithm> #include<stdio.h> u ...
- HDU - 1159 Common Subsequence (最长公共子序列)
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. ...
- nginx 配置 强制访问https
使用nginx的301状态码 server { listen ; if ($scheme = 'http') { return 301 https://$server_name$requ ...
- 论文阅读笔记(十一)【ICCV2017】:Jointly Attentive Spatial-Temporal Pooling Networks for Video-based Person Re-Identification
Introduction (1)Motivation: 当前采用CNN-RNN模型解决行人重识别问题仅仅提取单一视频序列的特征表示,而没有把视频序列匹配间的影响考虑在内,即在比较不同人的时候,根据不同 ...
- C++&C语言 -> //有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
/* a b c d 1 5 5 ...
- 爬虫学习笔记2requests库和beautifulsoup4库学习笔记
目录 1.requests库 1.1 安装 2.beautifulsoup4 2.1 常用方法 2.2 bs4 中四大对象种类 2.3 遍历文档树 2.4 搜索文档树 查询id=head的Tag 查询 ...
- spring框架中用到了哪些设计模式
1.代理模式:在AOP和remoting中被用的比较多 2.单例模式:在spring配置文件中定义的bean默认为单例模式 3.模板方法模式:解决代码重复问题 4.前端控制器模式:spring提供了D ...