Python提取非虚拟环境下项目所需依赖包

  • A+

Python提取非虚拟环境下项目所需依赖包

创建Python项目使用virtualenv虚拟环境工具管理依赖包很方便,但有时又懒得在每个项目的虚拟环境中多次重复pip安装各种包,于是直接在当前系统环境中建立了项目。这种方式很省事,但是如何提取每个项目使用到的依赖包呢?下面代码就是为了解决这个问题,直接输入项目app的路径,即可在项目目录下自动生成requirements.txt 依赖包文件。

原理是:首先遍历项目py文件并获得导入的模块名称,然后将系统通过pip freeze 生成的文件与项目中模块名称进行比照,最后根据比对结果生成该项目的依赖文件。

  1. #?-*-coding:utf-8-*-
  2. import?os
  3. import?re
  4. class?ReqTool(object):
  5. ????def?__init__(self,?project_path):
  6. ????????self.project_path?=?project_path
  7. ????????self.project_package?=?set()
  8. ????????self.package_name_version?=?list()
  9. ????????self.package_name?=?list()
  10. ????def?get_all_files(self,?project_path):
  11. ????????for?parent_path,?_,?files?in?os.walk(project_path):
  12. ????????????for?file?in?files:
  13. ????????????????file_name,?file_ext?=?os.path.splitext(file)
  14. ????????????????if?file_ext?==?'.py':
  15. ????????????????????file_abs_path?=?os.path.join(parent_path,?file)
  16. ????????????????????file_lines?=?self.get_import_file(file_abs_path)
  17. ????????????????????for?file_line?in?file_lines:
  18. ????????????????????????package?=?re.search(r'(from|import)?([a-zA-Z]\w*)',?file_line)
  19. ????????????????????????if?package:
  20. ????????????????????????????package_name?=?package.group().replace('from?',?'').replace('import?',?'').strip()
  21. ????????????????????????????if?package_name?in?self.package_name:
  22. ????????????????????????????????index?=?self.package_name.index(package_name)
  23. ????????????????????????????????self.project_package.add(self.package_name_version[index])
  24. ????def?write_requirements(self,?items):
  25. ????????with?open(self.project_path+'\\requirements.txt',?'w+')?as?file:
  26. ????????????for?item?in?items:
  27. ????????????????file.write(item)
  28. ????????????????file.write('\n')
  29. ????@staticmethod
  30. ????def?get_import_file(file):
  31. ????????with?open(file,?mode='r',?encoding='utf-8')?as?f:
  32. ????????????file_lines?=?f.readlines()
  33. ????????????return?file_lines
  34. ????def?read_all_requirements(self):
  35. ????????requirements_file_lines?=?os.popen('pip?freeze').read().strip().split('\n')
  36. ????????for?requirements_file_line?in?requirements_file_lines:
  37. ????????????self.package_name_version.append(requirements_file_line)
  38. ????????????self.package_name.append(requirements_file_line.split('==')[0])
  39. ????def?main(self):
  40. ????????self.read_all_requirements()
  41. ????????self.get_all_files(self.project_path)
  42. ????????self.write_requirements(self.project_package)
  43. if?__name__?==?'__main__':
  44. ????req_tool?=?ReqTool("D:\\github\\bdmaster\\app")
  45. ????req_tool.main()
  • 我的微信
  • 这是我的微信扫一扫
  • weinxin
  • 我的微信公众号
  • 我的微信公众号扫一扫
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: