- A+
所属分类:python实战案例 编程语言
创建Python项目使用virtualenv虚拟环境工具管理依赖包很方便,但有时又懒得在每个项目的虚拟环境中多次重复pip安装各种包,于是直接在当前系统环境中建立了项目。这种方式很省事,但是如何提取每个项目使用到的依赖包呢?下面代码就是为了解决这个问题,直接输入项目app的路径,即可在项目目录下自动生成requirements.txt 依赖包文件。
原理是:首先遍历项目py文件并获得导入的模块名称,然后将系统通过pip freeze 生成的文件与项目中模块名称进行比照,最后根据比对结果生成该项目的依赖文件。
- # -*-coding:utf-8-*-
- import os
- import re
- class ReqTool(object):
- def __init__(self, project_path):
- self.project_path = project_path
- self.project_package = set()
- self.package_name_version = list()
- self.package_name = list()
- def get_all_files(self, project_path):
- for parent_path, _, files in os.walk(project_path):
- for file in files:
- file_name, file_ext = os.path.splitext(file)
- if file_ext == '.py':
- file_abs_path = os.path.join(parent_path, file)
- file_lines = self.get_import_file(file_abs_path)
- for file_line in file_lines:
- package = re.search(r'(from|import) ([a-zA-Z]\w*)', file_line)
- if package:
- package_name = package.group().replace('from ', '').replace('import ', '').strip()
- if package_name in self.package_name:
- index = self.package_name.index(package_name)
- self.project_package.add(self.package_name_version[index])
- def write_requirements(self, items):
- with open(self.project_path+'\\requirements.txt', 'w+') as file:
- for item in items:
- file.write(item)
- file.write('\n')
- @staticmethod
- def get_import_file(file):
- with open(file, mode='r', encoding='utf-8') as f:
- file_lines = f.readlines()
- return file_lines
- def read_all_requirements(self):
- requirements_file_lines = os.popen('pip freeze').read().strip().split('\n')
- for requirements_file_line in requirements_file_lines:
- self.package_name_version.append(requirements_file_line)
- self.package_name.append(requirements_file_line.split('==')[0])
- def main(self):
- self.read_all_requirements()
- self.get_all_files(self.project_path)
- self.write_requirements(self.project_package)
- if __name__ == '__main__':
- req_tool = ReqTool("D:\\github\\bdmaster\\app")
- req_tool.main()
我的微信公众号
爱真理,得永生! 爱在灵灵久博客,网罗天下,福利大家!