python生成器/yield協(xié)程/gevent寫簡單的圖片下載器功能示例
本文實例講述了python生成器/yield協(xié)程/gevent寫簡單的圖片下載器功能。分享給大家供大家參考,具體如下:
1、生成器:
'''第二種生成器'''
# 函數(shù)只有有yield存在就是生成器
def test(i):
while True:
i += 1
res = yield i
print(res)
i += 1
return res
def main():
t = test(1) # 創(chuàng)建生成器對象
print(next(t)) # next第一次執(zhí)行從上到下,yield是終點
print(next(t))
print(t.send(5))
if __name__ == '__main__':
main()
運行結(jié)果:
2
None
4
5
6
2、yield協(xié)程demo:
def run1():
while True:
print('run1____')
yield
def run2():
while True:
print('run2____')
yield
def main():
while True:
next(run1())
next(run2())
if __name__ == '__main__':
main()
3、gevent寫簡單的下載圖片
import gevent
import requests,lxml
# from gevent import monkey
# monkey.patch_all()
def get_pic(url, list):
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
response = requests.get(url, headers=headers)
with open('./pic/'+str(list.pop(0)) + '.png', 'wb') as f:
f.write(response.content)
def get_pic_name_list():
def main():
get_pic_name_list()
list = [x for x in range(9999)]
gevent.joinall([
gevent.spawn(get_pic, 'http://pic8.iqiyipic.com/image/20181008/eb/af/v_116880780_m_601_m11_180_236.jpg', list),
gevent.spawn(get_pic, 'http://pic6.iqiyipic.com/image/20181004/a2/2b/v_112874372_m_601_m15_180_236.jpg', list)
])
if __name__ == '__main__':
main()
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python實現(xiàn)視頻讀取和轉(zhuǎn)化圖片
今天小編就為大家分享一篇python實現(xiàn)視頻讀取和轉(zhuǎn)化圖片,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python爬蟲的兩套解析方法和四種爬蟲實現(xiàn)過程
本文想針對某一網(wǎng)頁對 python 基礎(chǔ)爬蟲的兩大解析庫( BeautifulSoup 和 lxml )和幾種信息提取實現(xiàn)方法進(jìn)行分析,及同一網(wǎng)頁爬蟲的四種實現(xiàn)方式,需要的朋友參考下吧2018-07-07
利用python實現(xiàn)詞頻統(tǒng)計分析的代碼示例
詞頻統(tǒng)計是指在文本或語音數(shù)據(jù)中,統(tǒng)計每個單詞或符號出現(xiàn)的次數(shù),以便對文本或語音數(shù)據(jù)進(jìn),這篇文章將詳細(xì)介紹分詞后如何進(jìn)行詞頻統(tǒng)計分析2023-06-06
python 實現(xiàn)rolling和apply函數(shù)的向下取值操作
這篇文章主要介紹了python 實現(xiàn)rolling和apply函數(shù)的向下取值操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

