簡體   English   中英

Python 3多重處理-如何執行單個任務

[英]Python 3 Multiprocessing - how to execute a single task

提前感謝!

任務說明:我想使用Python收集免費的https代理服務器信息並進行測試。 這些代碼需要花費幾分鍾的時間(大約要測試100個代理服務器),我知道多處理可以顯着提高執行速度,但是,我嘗試了幾天卻沒有運氣……似乎所有子流程都在重復任務,而不是一起做。

在這里需要協助...

代碼:

import requests
import re
import telnetlib
import multiprocessing

def run(info1, info2):
    try:
        tn = telnetlib.Telnet(info1, port= info2, timeout= 2)
    except:
        print('not working !')
    else:
        proxy_server = 'http://' + info1 + ':' + info2
        print(proxy_server)

if __name__=='__main__':
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'}
    html = requests.get('https://www.sslproxies.org', headers=headers, allow_redirects=False)
    pattern = re.compile('<td>(\d.*?)</td><td>(\d+)</td>', re.S)
    items = re.findall(pattern, html.text)
    for item in items:
        for i in range(5):
            p = multiprocessing.Process(target=run(item[0], item[1]), args=('msc%s' % i,))
            p.start()

您的任務基本上是IO綁定的(您正在從許多遠程服務器請求信息),因此您需要“同時”請求所有服務器並等待它們的答復。 這是典型的用例,您應在其中使用諸如Python之類的語言的並發功能。 某種程度上,多處理是實現並發的一種方法(嚴格來說,這樣的斷言是不正確的),但是如果您需要請求成千上萬的服務器會發生什么呢? 創建數以千計的過程不是一個好方法。

我推薦這篇文章: https : //pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html

這將幫助您以非常有效的方式實現您要完成的任務。

“ for i在range(5)中”生成5次相同的過程,從而產生重復。 只需刪除它並以更簡單的方式創建過程即可實現。

    for item in items:
            p = multiprocessing.Process(target=run, args=(item[0], item[1],))
            p.start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM