当前位置 博文首页 > qq262593421的博客:win10使用脚本批量下载本机python依赖包

    qq262593421的博客:win10使用脚本批量下载本机python依赖包

    作者:[db:作者] 时间:2021-08-17 21:44

    问题描述

    很多公司的生成环境都需要离线安装
    如何快速将windows下的python依赖包下载到本地呢?

    问题解决

    将本机的python依赖包写入txt
    使用python脚本处理txt依赖包格式
    使用bat脚本批量读取并下载依赖包

    详细步骤

    1、将本机依赖导入txt

    pip list > denpend.txt
    cat depend.txt

    2、去除依赖版本

    忽略版本:打开denpend.txt把版本号和空格去掉
    指定版本:使用python脚本

    replace.py

    #-*- encoding: utf-8 -*-
    
    def isonesplace(str):
        """判断字符串是否只有一个空格"""
        str = str.split(" ")
        return len(str)
    
    def func(str):
        """将中间的空格替换成双等号=="""
        str = str.strip()
        while("==" not in str and isonesplace(str) != 2):
            str = str.replace("  ", " ")
        return str.replace(" ", "==")
    
    def readfile(file):
        """返回file文件去除前两行和全部空格的字符串"""
        ## 读取depend.txt到list
        fr = open(file, 'r', encoding='utf-8')
        list = fr.readlines()
        fr.close()
        comment = ""
        num = 0
        ## 去除前两行和空格,将读取内容存入变量
        for i in list:
            num += 1
            if num > 2:
                row = i.strip()
                comment += row + "\n"
        # print(comment)
        return comment
    
    def writefile(file, str):
        """将str字符串写入file文件"""
        comment = ""
        str = str.split("\n")
        num = 1
        for row in str:
            num += 1
            if (row is ""):
                break
            if(num < len(str)):
                comment += func(row) + "\n"
            else:
                comment += func(row)
        print(comment)
        # # 清空depend.txt
        # open(file, 'w').close()
        # 将comment重新写入depend.txt
        fw = open(file, 'w')
        with fw as f:
            f.write(comment)
        # fw.write(comment)
        fw.close()
    
    if __name__ == "__main__":
        print("----------starting procedure---------")
        file = "depend.txt"
        str = readfile(file)
        writefile(file, str)
        print("----------termination routine--------")

    执行脚本

    python replace.py

    ?3、bat脚本下载

    download.bat

    @echo off
    REM for /f %%i in ('cat depend.txt') do echo "pip download %%i"
    for /f %%i in ('cat depend.txt') do echo %%i
    for /f %%i in ('cat depend.txt') do pip download %%i
    pause

    4、文件目录

    脚本说明

    depend.txt:将本机python依赖包写入depend.txt
    replace.py:将depend.txt替换成pip识别的版本名
    download.bat:批量下载本机python离线安装包脚本

    执行前

    执行后

    ?

    cs