亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

Python用多進(jìn)程寫文件遇到編碼問題,而用多線程卻不會(huì)

瀏覽:115日期:2022-06-28 13:29:55

問題描述

用多進(jìn)程爬取數(shù)據(jù)寫入文件,運(yùn)行沒有報(bào)錯(cuò),但是打開文件卻亂碼。Python用多進(jìn)程寫文件遇到編碼問題,而用多線程卻不會(huì)

Python用多進(jìn)程寫文件遇到編碼問題,而用多線程卻不會(huì)

用多線程改寫時(shí)卻沒有這個(gè)問題,一切正常。下面是數(shù)據(jù)寫入文件的代碼:

def Get_urls(start_page,end_page): print ’ run task {} ({})’.format(start_page,os.getpid()) url_text = codecs.open(’url.txt’,’a’,’utf-8’)for i in range(start_page,end_page+1): pageurl=baseurl1+str(i)+baseurl2+searchword response = requests.get(pageurl, headers=header) soup = BeautifulSoup(response.content, ’html.parser’) a_list=soup.find_all(’a’) for a in a_list:if a.text!=’’and ’wssd_content.jsp?bookid’in a[’href’]: text=a.text.strip() url=baseurl+str(a[’href’]) url_text.write(text+’t’+url+’n’)url_text.close()

多進(jìn)程用的進(jìn)程池

def Multiple_processes_test(): t1 = time.time() print ’parent process {} ’.format(os.getpid()) page_ranges_list = [(1,3),(4,6),(7,9)] pool = multiprocessing.Pool(processes=3) for page_range in page_ranges_list:pool.apply_async(func=Get_urls,args=(page_range[0],page_range[1])) pool.close() pool.join() t2 = time.time() print ’時(shí)間:’,t2-t1

問題解答

回答1:

圖片上已經(jīng)說了,文件以錯(cuò)誤的編碼形式載入了,說明你多進(jìn)程寫入的時(shí)候,編碼不是utf-8

回答2:

文件第一行添加:

#coding: utf-8回答3:

打開同一個(gè)文件,相當(dāng)危險(xiǎn),出錯(cuò)機(jī)率相當(dāng)大,多線程不出錯(cuò),極有可能是GIL,多進(jìn)程沒有鎖,因此容易出錯(cuò)了。

url_text = codecs.open(’url.txt’,’a’,’utf-8’)

建議改為生產(chǎn)者消費(fèi)都模式!

比如這樣

# -*- coding: utf-8 -* -import timeimport osimport codecsimport multiprocessingimport requestsfrom bs4 import BeautifulSoupbaseurl = ’’baseurl1 = ’’baseurl2 = ’’pageurl = ’’searchword = ’’header = {}def fake(url, **kwargs): class Response(object):pass o = Response() o.content = ’<a href='http://www.aoyou183.cn/{}/wssd_content.jsp?bookid'>foo</a>’.format(url) return orequests.get = fakedef Get_urls(start_page, end_page, queue): print(’run task {} ({})’.format(start_page, os.getpid())) try:for i in range(start_page, end_page + 1): pageurl = baseurl1 + str(i) + baseurl2 + searchword response = requests.get(pageurl, headers=header) soup = BeautifulSoup(response.content, ’html.parser’) a_list = soup.find_all(’a’) for a in a_list:if a.text != ’’and ’wssd_content.jsp?bookid’in a[’href’]: text = a.text.strip() url = baseurl + str(a[’href’]) queue.put(text + ’t’ + url + ’n’) except Exception as e:import tracebacktraceback.print_exc()def write_file(queue): print('start write file') url_text = codecs.open(’url.txt’, ’a’, ’utf-8’) while True:line = queue.get()if line is None: breakprint('write {}'.format(line))url_text.write(line) url_text.close()def Multiple_processes_test(): t1 = time.time() manager = multiprocessing.Manager() queue = manager.Queue() print ’parent process {} ’.format(os.getpid()) page_ranges_list = [(1, 3), (4, 6), (7, 9)] consumer = multiprocessing.Process(target=write_file, args=(queue,)) consumer.start() pool = multiprocessing.Pool(processes=3) results = [] for page_range in page_ranges_list:result = pool.apply_async(func=Get_urls, args=(page_range[0], page_range[1], queue ))results.append(result) pool.close() pool.join() queue.put(None) consumer.join() t2 = time.time() print ’時(shí)間:’, t2 - t1if __name__ == ’__main__’: Multiple_processes_test()結(jié)果

foo /4/wssd_content.jsp?bookidfoo /5/wssd_content.jsp?bookidfoo /6/wssd_content.jsp?bookidfoo /1/wssd_content.jsp?bookidfoo /2/wssd_content.jsp?bookidfoo /3/wssd_content.jsp?bookidfoo /7/wssd_content.jsp?bookidfoo /8/wssd_content.jsp?bookidfoo /9/wssd_content.jsp?bookid

標(biāo)簽: Python 編程
主站蜘蛛池模板: 日本欧美成人免费观看 | 国产日韩精品一区二区在线观看播放 | 亚洲欧美国产精品久久久 | 久久免费精品国产72精品剧情 | 精品国产区 | 免费一级毛片视频 | 小明精品国产一区二区三区 | 中文字幕无线码一区二区三区 | 性欧美视频在线观看 | 亚洲第成色999久久网站 | 国产精品久久永久免费 | 亚洲精品一区乱码在线观看 | 久久这里有精品 | 96精品视频在线播放免费观看 | 国产精品三 | 日本一级看片免费播放 | 特级黄色一级片 | 亚洲精品色综合久久久 | 免费在线观看黄色的网站 | 国产九九在线观看播放 | 亚洲国产人成在线观看 | 国外成人在线视频 | 久久精品一区二区三区不卡 | 久久亚洲国产成人精品性色 | 久久成人国产精品免费 | 免费无毒片在线观看 | 欧美日韩一区二区三区毛片 | 亚洲福利一区二区 | 黄色篇| 女人18毛片a级毛片免费视频 | 亚洲一区二区三区成人 | 久久久久精彩视频 | 一级一级特黄女人精品毛片视频 | 日韩色视频在线观看 | 国模私拍福利视频在线透漏 | 国产成人亚洲精品无广告 | 亚洲大尺度在线观看 | 九九热视频在线播放 | 国产大尺度福利视频在线观看 | 国产露脸150部国语对白 | 生活一级毛片 |