Python:requirements.txt依赖文件生成

发布于:2025-08-15 ⋅ 阅读:(17) ⋅ 点赞:(0)

大家在使用别人的代码时,都需要用到一个文件就是requirements.txt,用于安装代码对应的环境依赖包。同样的,当我们需要将自己的代码给别人用,或者是需要打包部署docker等,都需要在自己的项目下新建一个requirements.txt文件。

那么接下来就看看这个文件怎么生成

1. pip freeze

在命令行运行pip freeze可以列出当前虚拟环境中安装的所有 Python 包及其版本。这个命令在创建项目的依赖清单(requirements.txt)时非常有用,以便在其他环境中重新安装相同的依赖包。

用pycharm打开项目,点击下方的terminal打开终端,或者是在命令行启动虚拟环境都可以,然后运行pip freeze

输入下面这句就可以生成文件了

pip freeze > requirements.txt

但是该方法会将环境中的所有包都导入到文件中,很显然有时候我们一般只需要当前项目运行所依赖的包,那么可以看看下面这个方法

2.使用三方库pipreqs

先安装

pip install pipreqs

在当前目录使用pipreqs命令:

pipreqs ./ --encoding=utf8  --force
–encoding=utf8 :使用utf8编码
–force :强制执行,当 生成目录下的requirements.txt存在时覆盖
. /: 在哪个路径下生成requirements.txt 文件

这时候再打开文件就会发现只有项目需要的库了

3.问题解决

有时候会遇到报错

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 154: invalid start byte

3.1 修改编码

可以尝试用别的编码形式

pipreqs ./ --encoding=gbk --force

pipreqs ./ --encoding=iso-8859-1  --force 

3.2 筛查问题文件

写一个筛选问题文件的脚本

import os
from chardet import detect

for root, dirs, files in os.walk("."):
    for file in files:
        if not file.endswith(".py"):  # 只检查Python文件
            continue
        path = os.path.join(root, file)
        try:
            with open(path, "rb") as f:
                raw = f.read()
                detect(raw)  # 尝试检测编码
        except Exception as e:
            print(f"Bad file: {path} - Error: {str(e)}")

如果明显有问题但运行脚本没有打印问题文件,可以尝试修改源码

3.3 修改源码

注意!!修改完一定要记得改回来!!!

查找源代码中的read_file_content方法

# 源代码
def read_file_content(file_name: str, encoding="utf-8"):
    if file_ext_is_allowed(file_name, DEFAULT_EXTENSIONS):
        with open(file_name, "r", encoding=encoding) as f:
            contents = f.read()
    elif file_ext_is_allowed(file_name, [".ipynb"]) and scan_noteboooks:
        contents = ipynb_2_py(file_name, encoding=encoding)
    return contents

添加try except:

def read_file_content(file_name: str, encoding="utf-8"):
    try:
        if file_ext_is_allowed(file_name, DEFAULT_EXTENSIONS):
            with open(file_name, "r", encoding=encoding) as f:
                contents = f.read()
        elif file_ext_is_allowed(file_name, [".ipynb"]) and scan_noteboooks:
            contents = ipynb_2_py(file_name, encoding=encoding)
        return contents
    except UnicodeDecodeError as e:
        print(f"!!! 编码错误文件: {file_name} !!!")  # 添加这行
        raise e

此时再在终端运行

pipreqs ./ --encoding=utf8  --force

会打印出问题文件,如:

此时再运行指令忽略对应的文件或文件夹

pipreqs ./ --encoding=utf8 --force --ignore=work_dirs,configs,clrnet.egg-info,cache,.eggs

requirements.txt文件就生成成功啦


网站公告

今日签到

点亮在社区的每一天
去签到