Python 多进程

2018-04-19 17:17:34 +08:00
 Meli55a

需求:批量检测 url 有效性

我有一个文本中有 10w 条网址,需要检测所有 url 是否能打开,并将能打开的 url 保存到文本中,不了解 python 的多进程,网上看了一些文章,有些懵逼,求指点

原代码如下:

import requests

url_result_success = []
url_result_failed = []

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, compress',
    'Accept-Language': 'en-us;q=0.5,en;q=0.3',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0'
}

with open(r'urls.txt', 'r') as f:
    for url in f:
        url = url.strip()
        print url
        try:
            response = requests.get(url, headers=headers, allow_redirects=True, timeout=5)
            if response.status_code != 200:
                raise requests.RequestException(u"Status code error: {}".format(response.status_code))
        except requests.RequestException as e:
            url_result_failed.append(url)
            continue
        url_result_success.append(url)

with open(r'valid_urls.txt', 'a+') as f:
    for url in url_result_success:
        url = url.strip()
        f.write(url + '\n')
3762 次点击
所在节点    Python
23 条回复
zmj1316
2018-04-19 18:18:59 +08:00
IO 密集的不需要多进程,多线程甚至异步都可以
skyleft
2018-04-19 18:25:02 +08:00
gevent
Nubia
2018-04-19 18:34:48 +08:00
request 会阻塞 上 aiohttp 吧
albertofwb
2018-04-19 18:35:20 +08:00
gevent 略重,async 了解下,python3.6+ 自带
TheCure
2018-04-19 18:40:12 +08:00
golang 了解下
wzwwzw
2018-04-19 18:50:02 +08:00
asyncio + aiohttp 了解下。
doubleflower
2018-04-19 18:57:49 +08:00
开一百个线程就行,10w 没多久
cszhiyue
2018-04-19 19:06:45 +08:00
这并不是 cpu 密集的程序考虑 线程 或者 异步
lusi1990
2018-04-19 20:32:01 +08:00
可以使用 head 代替 get,用多线程就可以,时间看带宽
ToT
2018-04-19 22:19:15 +08:00
多线程即可,多进程会受限于你 CPU 的数目。
Meli55a
2018-04-19 22:50:04 +08:00
@zmj1316 @Nubia @albertofwb @wzwwzw 代码要在 2003 上跑,没法装 3.6.。。
@doubleflower @cszhiyue @ToT 嗯,用多线程
@skyleft 找到过相关文章,值得研究
@lusi1990 你说的知道,但没有深入看
下午小区周边光纤让修地铁的干断了,才来的网。。。。
ClutchBear
2018-04-19 22:58:57 +08:00
生产者 消费者模式的多线程就行,
用 queue 队列存取数据
生产者往 queue 里面存数据,
消费者里面用一个 while True 死循环 从 queue 里面取数据.
设置一个终止的毒丸.
Meli55a
2018-04-19 23:07:08 +08:00
@ClutchBear 要恶补基础知识了。。
ClutchBear
2018-04-19 23:07:37 +08:00

类似这样, 把读文件替换到 生产者里面,
requests 验证放到消费者里面
Meli55a
2018-04-19 23:07:52 +08:00
@ClutchBear 有推荐的书看么,程序设计模式之类的
ClutchBear
2018-04-19 23:09:33 +08:00
@Meli55a 多线程不需要书啊, 最基本的生产者 消费者模式,
java python 都是一样的.
Meli55a
2018-04-19 23:16:57 +08:00
@ClutchBear 好的,我好好看看你的代码,感谢!~
claysec
2018-04-19 23:54:01 +08:00
@ClutchBear 我想了解下这两个 join 函数的意义是什么呢。萌新一时没看懂
orangeade
2018-04-19 23:55:31 +08:00
Python 里用多进程多线程直接上 concurrent future,基本上不用关心啥细节
so1n
2018-04-20 00:23:39 +08:00
Aiohttp 了解下。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/448198

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX