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

背景

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

环境

系统: windows 10

python版本: 3.6.8

核心

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

脚本

新建文件 testone.py

  1. # encoding:utf-8
  2. # -*- coding: UTF-8 -*-
  3. # Author:PC-Jruing
  4. # FileName:testone
  5. # DateTime:2021/7/23 18:54
  6. # SoftWare: PyCharm
  7. import os, sys
  8. requires_set = []
  9. # 查询依赖
  10. def Dependent_query(pkg_name):
  11. Output = os.popen(f"pip show {pkg_name}")
  12. Requires = Output.readlines()
  13. for line in Requires:
  14. # 读取依赖包名称
  15. if "Requires:" in line:
  16. requires_list = line.strip().split(':')[1].split(',')
  17. requires_list = [i for i in requires_list if i]
  18. if requires_list:
  19. for requires in requires_list:
  20. if requires:
  21. requires_set.append(requires.strip())
  22. Dependent_query(requires.strip())
  23. def download(requires_set):
  24. if isinstance(requires_set, list) and requires_set:
  25. for pkg in requires_set:
  26. print(f"==========开始下载{pkg}==========")
  27. pkg_Output = os.system(f"pip download {pkg}")
  28. print(pkg_Output)
  29. if __name__ == '__main__':
  30. pkg_name = sys.argv[1]
  31. requires_set.append(pkg_name)
  32. # 查询依赖包
  33. Dependent_query(pkg_name)
  34. print(f"安装顺序参考:{requires_set[::-1]}")
  35. # 启用下载依赖包功能
  36. # download(requires_set)

执行: python testone.py requests