Python進程池中實現進度條顯示


Python進程池中實現進度條顯示

  今天使用進程池爬蟲,爬的網頁太多,想通過進度條來顯示出來,但是發現並沒有想象的那么簡單。

  Python中多進程使用Queue來數據共享,進程池使用Manager().Queue()來實現數據共享,如果想使用進程回調函數,則進程函數一定要返回參數。

  最后在github一段下面找到解決代碼,如下:

import time
import random
from multiprocessing import Pool
from tqdm import tqdm

def myfunc(a):
    time.sleep(random.random())
    return a ** 2

if __name__ == '__main__':
    pool = Pool(2)
    '''
    for _ in tqdm(pool.imap_unordered(myfunc, range(100)), total=100):
        pass
    '''
    pbar = tqdm(total=100)
    def update(*a):
        pbar.update()
        # tqdm.write(str(a))
    for i in range(pbar.total):
        pool.apply_async(myfunc, args=(i,), callback=update)
    # tqdm.write('scheduled')
    pool.close()
    pool.join()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM