多线程下载文件dome

由于未提供博客具体内容,无法给出包含关键信息的摘要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import os
import threading
import requests
import time

# 线程数
thread_num = 10
name = 0
cur_path = os.path.dirname(os.path.realpath(__file__))
log_path = os.path.join(cur_path, 'output')
if not os.path.exists(log_path): os.mkdir(log_path)


def download(img_url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0"
    }
    response = requests.get(url=img_url, headers=headers, timeout=5, stream=True)
    global name
    name = name + 1
    with open("./output/%d.jpg" % name, "wb") as f:
        f.write(response.content)
        time.sleep(0.01)


def get_imgurl_generate():
    with open('./url_new.txt', 'r') as f:
        for line in f:
            line = line.strip()
            if len(line) > 5:
                yield line
            else:
                continue


lock = threading.Lock()


def loop(imgs):
    print('thread %s is running...' % threading.current_thread().name)

    while True:
        try:
            with lock:
                # img_url, img_name = next(imgs)
                img_url = next(imgs)
        except StopIteration:
            break
        try:
            download(img_url)
        except:
            print('exceptfail\t%s' % img_url)
        # download(img_url)
    print('thread %s is end...' % threading.current_thread().name)


img_gen = get_imgurl_generate()

for i in range(0, thread_num):
    t = threading.Thread(target=loop, name='LoopThread %s' % i, args=(img_gen,))
    t.start()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值