Python 查询第三方包依赖及下载

Python 查询第三方包依赖及下载

背景

内网环境/无网环境安装python第三方包的时候太麻烦,比如requests,他需要依赖 charset-normalizer, urllib3, certifi, idna, 安装流程可能变成 安装requests->缺少包->下载缺少的包->安装,不断的重复这个步骤,所以为了解决这个问题 ,写出来如下脚本,然后在本地执行,将下载的包通过ftp传递到服务器上

环境

系统: windows 10

python版本: 3.6.8

核心

依赖 pip show 和pip download 这两个命令

脚本

新建文件 testone.py

# encoding:utf-8
# -*- coding: UTF-8 -*-    
# Author:PC-Jruing
# FileName:testone
# DateTime:2021/7/23 18:54
# SoftWare: PyCharm


import os, sys

requires_set = []


def Dependent_query(pkg_name):
    Output = os.popen(f"pip show {pkg_name}")
    Requires = Output.readlines()
    for line in Requires:
        if "Requires:" in line:
            requires_list = line.strip().split(':')[1].split(',')
            requires_list = [i for i in requires_list if i]
            if requires_list:
                for requires in requires_list:
                    if requires:
                        requires_set.append(requires.strip())
                        Dependent_query(requires.strip())


def download(requires_set):
    if isinstance(requires_set, list) and requires_set:
        for pkg in requires_set:
            print(f"==========开始下载{pkg}==========")
            pkg_Output = os.system(f"pip download {pkg}")
            print(pkg_Output)


if __name__ == '__main__':
    pkg_name = sys.argv[1]
    requires_set.append(pkg_name)
    # 查询依赖包
    Dependent_query(pkg_name)
    print(f"安装顺序参考:{requires_set[::-1]}")
    # 启用下载依赖包功能
    # download(requires_set)

执行: python testone.py requests

posted @ 2021-07-26 10:39  Jruing  阅读(822)  评论(0编辑  收藏  举报