题目:
# 编写一个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 == 200:
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.')