当前位置:   article > 正文

python如何快速生成一个requirements.txt_python生成requirements.txt

python生成requirements.txt

一、使用方法

先安装

pip install requirementsGet -i https://pypi.tuna.tsinghua.edu.cn/simple/
  • 1

然后在你要生成requirements.txt的项目根目录下新建一个文件

[make_requirements.py]
import requirementsGet
requirementsGet.get()
  • 1
  • 2
  • 3

然后运行这个python文件即可

二、实现原理

一、文件夹遍历

首先通过以下代码拿到项目下所有python文件

def traverse_files(directory):
    for file_name in os.listdir(directory):
        file_path = os.path.join(directory, file_name)
        if os.path.isdir(file_path):
            for i in traverse_files(file_path):
                yield i
        else:
            # 在这里可以对文件进行操作
            if file_path.endswith(".py"):
                yield file_path
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

二、获取导入名

进行迭代,通过文件中的import,frome等字段,提取出导入名

def get_import(f):
    imports = []
    for line in f.split("\n"):
        if "".join(list(line)[0:5]) == "from " and "import " in line:
            line = (
                line.replace("from", "")
                .split("import")[0]
                .replace(" ", "")
                .split(".")[0]
            )
            imports.append(line)
        elif "".join(list(line)[0:7]) == "import ":
            line = line.replace("import", "")
            for item in line.split(","):
                item = item.split(" as ")[0].replace(" ", "").split(".")[0]
                imports.append(item)
    return list(set(imports))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

三、获取安装名

许多库的导入名和安装名不同,如PIL的安装名是pillow,可以通过遍历site-packages下的top_level.txt文件,实现获取安装名,但是也有一些是无法获取到的,比如bs4->beautifulsoup4,可以通过在LEVE_TOP_FORMAT 中添加内容来实现,代码里内置了几个,可以自行添加更多或按如下方式临时添加

[make_requirements.py]
import requirementsGet
requirementsGet.LEVE_TOP_FORMAT ["bs4"] = "beautifulsoup4"
  • 1
  • 2
  • 3

获取top_level.txt代码如下

def init_top_leves():
    directory = sysconfig.get_paths()["purelib"]
    for file_name in os.listdir(directory):
        file_path = os.path.join(directory, file_name)
        if (
            os.path.isdir(file_path)
            and "dist-info" in file_path
            and os.path.exists(file_path + "/top_level.txt")
        ):
            top_levels = (
                open(file_path + "/top_level.txt", "r", encoding="utf-8")
                .read()
                .split("\n")
            )
            package_name = file_path.replace("\\", "/").split("/")
            package_name = package_name[package_name.__len__() - 1].split("-")[0]
            for top_level in top_levels:
                if not top_level:
                    continue
                LEVE_TOP_FORMAT[top_level] = package_name
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

四、获取版本

大部分版本可以通过以下代码获取,没有获取到的问题也不大

item = "bs4"
version = inspect.getmodule(import_module(item)).__version__
  • 1
  • 2

结束

最后运行结果如下

requests==2.31.0
PyExecJS
colorlog
PyYAML==6.0
beautifulsoup4==4.12.2
urllib3==1.26.16

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/810545
推荐阅读
相关标签
  

闽ICP备14008679号