You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Pool.imap中传递序号重命名下载的TS文件?

解决方案

要实现用有序序号命名TS文件,你需要修改download_ts_file函数接收序号参数,并在调用时给每个URL分配对应序号,具体步骤如下:

修改下载函数

新增index参数,用它生成001.ts格式的有序文件名,同时保留原文件名用于错误排查:

def download_ts_file(ts_url: str, store_dir: str, index: int, attempts: int = 10):
    # 生成三位数字的有序文件名,如001.ts、002.ts
    ts_fname = f"{index:03d}.ts"
    ts_dir = os.path.join(store_dir, ts_fname)
    # 保留原URL的文件名,用于下载失败时提示
    original_fname = ts_url.split('/')[-1]
    ts_res = None

    for _ in range(attempts):
        try:
            ts_res = requests.get(ts_url, headers=header)
            if ts_res.status_code == 200:
                break
        except Exception:
            pass
        time.sleep(.5)

    if isinstance(ts_res, Response) and ts_res.status_code == 200:
        with open(ts_dir, 'wb+') as f:
            f.write(ts_res.content)
    else:
        print(f"Failed to download streaming file: {original_fname} (target filename: {ts_fname}).")

修改多进程调用逻辑

用enumerate给每个URL分配从1开始的序号,通过包装函数将URL和序号一起传递给下载函数:

from functools import partial
from multiprocessing import Pool
import tqdm
from requests.models import Response
import os
import time
import requests

# 假设ts_url_list是你的TS文件URL列表
ts_url_list = [...]  # 替换为你的实际URL列表
header = {...}  # 替换为你的请求头

pool = Pool(20)
# 给每个URL绑定从1开始的序号
tasks = enumerate(ts_url_list, start=1)
# 预先绑定存储目录参数
bound_download = partial(download_ts_file, store_dir='.')

# 包装函数,解包URL和序号并调用下载函数
def task_wrapper(args):
    url, idx = args
    bound_download(url, index=idx)

# 执行多进程下载并显示进度
gen = pool.imap(task_wrapper, tasks)
for _ in tqdm.tqdm(gen, total=len(ts_url_list)):
    pass
pool.close()
pool.join()

关键说明

  • {index:03d}.ts确保序号是三位数字,避免合并时出现排序混乱(如1.ts排在10.ts后面)
  • 保留原文件名的错误提示,方便定位哪个URL下载失败
  • 用enumerate(start=1)让序号从1开始,符合常规的文件命名习惯(若需从0开始,移除start=1即可)

内容的提问来源于stack exchange,提问作者mikezang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 23:52:46