1. 程式人生 > >python用map()函式和多執行緒threading、Thread採集注意事項

python用map()函式和多執行緒threading、Thread採集注意事項

import re
import requests
from threading import Thread


def getUrl():
    url = 'http://www.xiaohuar.com/2014.html'
    html = requests.get(url)
    list_img = re.findall('class="img".*?<img.*?src="(http://www.xiaohuar.com.*?)"', html.text, re.S)
    return list_img


def downImg(img):
    result = requests.
get(img) name = img.split('/')[-1] with open(name, 'wb') as f: f.write(result.content) print('下載完成', name) def th(img): t = Thread(target=downImg, args=(img,)) t.start() list_img = getUrl() list(map(th, list_img)) print('main thread')

注意:python3中 map()返回的是迭代器,不是列表,用for或者list進行迭代操作 list(map(th, list_img)) 主執行緒會先結束print(‘main thread’),等待子執行緒用join方法 args引數是元組,所以傳(img,)