OpenCV在CMake时出现文件无法下载的解决办法(利用python自动下载脚本)

 wongkai@hnu.edu.cn

# Download external libraries that are needed for the Cmake build
# but cmake cannot download due to network issues.
# make sure you can visit download link via your browser

import hashlib
import re
import sys
from pathlib import Path

import requests


def get_size(file_url):
    head = requests.head(file_url)
    return int(head.headers['Content-Length'])  # in bytes


def format_size(size):
    import math
    p = int(math.log(size, 1024))
    return str(round(size / math.pow(1024, p), 2)) + " " + ["B", "KB", "MB", "GB", "TB", "PB", "EB"][p]


log_path = Path(input("Enter the path to the log file: "))
# log_path = Path(sys.argv[1])

with open(log_path, "r") as log_file:
    log = log_file.read()

tasks = [[Path(eval(task[0])), eval(task[1])] for task in
         [s.split()[1:] for s in re.findall(r'#cmake_download\s\".*\"', log)]]

print("Found {} failed task".format(len(tasks)) + "s" * bool(len(tasks) > 1))

if len(tasks) == 0:
    print("Done")
    sys.exit(0)

total_size = 0
for task in tasks:
    file_size = get_size(task[1])
    total_size += file_size
    print(f"{task[0].name.split('-')[-1]:<50}{format_size(file_size)}")

print("==============================================================================")
print(f"Total size: {format_size(total_size)}")

if input("Continue? [Y/n]: ") == "n":
    print("Done")
    sys.exit(0)
print("==============================================================================")

for task in tasks:
    path = task[0]
    url = task[1]
    file_name = path.name.split('-')[-1]
    file_md5 = path.name.split('-')[0]
    if path.exists() and hashlib.md5(path.read_bytes()).hexdigest() == file_md5:
        print("{} already exists, skipping...".format(path.name))
        continue
    print(f"Downloading {file_name} from {url}")
    r = requests.get(url)

    if r.raise_for_status():
        print(f"Failed to download {file_name} ({r.status_code})")
        continue
    else:
        print(f"Downloaded {file_name} successfully")
        with open(path, "wb") as f:
            f.write(r.content)

        print(f"Checking md5sum of {file_name}: {file_md5}")
        if file_md5 == hashlib.md5(r.content).hexdigest():
            print(f"md5sum of {file_name} is correct:{file_md5}")
            print(f"{file_name} has been written to {path}")
    print("==============================================================================")
print("\nDone")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值