优先推荐使用方法 1 或方法 3,即使用 pipreqs
或 PyCharm 工具扫描项目代码生成 requrements.txt
文件。
原因如下:
pip freeze
仅包含使用pip install
安装到 Python 环境的包pip freeze
会包含当前 Python 环境中的所有包,不爱考虑这些包是否在当前项目中使用,因此使用pip freeze
通常需要有 Python 的虚拟环境pip freeze
无法对一个没有安装环境的新项目创建requrements.txt
文件
但是,使用 pipreqs
仅能扫描到项目中直接引用的包,如果在引用的包中使用了该包依赖中没有的包,则这些包也无法被 pipreqs
找到。但是,在开发过程中,这些包可能在我们排查问题时已经安装到了 Python 环境中。此时,使用方法 2 可以包含这些包。例如,pandas
并没有依赖 openpyxl
,但在代码中可以选择使用 openpyxl
在解析 Excel 文件。
方法 1:使用 pipreqs
扫描项目代码生成
Step 1|安装 pipreqs
pip install pipreqs
Step 2|在 项目根目录 下,使用 pipreqs
扫描项目文件夹生成 requirements.txt
文件
pipreqs . --encoding=utf8
其中,.
表示当前目录。运行上述命令后,requrements.txt
文件将会生成在项目的根目录下。
pipreqs
的 Github 仓库:https://github.com/bndr/pipreqs
pipreqs 的参数说明如下:
Usage:
pipreqs [options] [<path>]
Arguments:
<path> The path to the directory containing the application files for which a requirements file
should be generated (defaults to the current working directory)
Options:
--use-local Use ONLY local package info instead of querying PyPI
--pypi-server <url> Use custom PyPi server
--proxy <url> Use Proxy, parameter will be passed to requests library. You can also just set the
environments parameter in your terminal:
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="https://10.10.1.10:1080"
--debug Print debug information
--ignore <dirs>... Ignore extra directories, each separated by a comma
--no-follow-links Do not follow symbolic links in the project
--encoding <charset> Use encoding parameter for file open
--savepath <file> Save the list of requirements in the given file
--print Output the list of requirements in the standard output
--force Overwrite existing requirements.txt
--diff <file> Compare modules in requirements.txt to project imports
--clean <file> Clean up requirements.txt by removing modules that are not imported in project
--mode <scheme> Enables dynamic versioning with <compat>, <gt> or <non-pin> schemes
<compat> | e.g. Flask~=1.1.2
<gt> | e.g. Flask>=1.1.2
<no-pin> | e.g. Flask
--scan-notebooks Look for imports in jupyter notebook files.
方法 2:使用 pip freeze
生成
这个方法会将当前 Python 环境中所有已安装的包添加的 requirements.txt
文件中,如果运行该命令的 Python 环境不是为当前项目搭建的虚拟环境,则会导致大量当前项目不需要的包被添加到 requirements.txt
中。
Step 1|进入虚拟环境
Step 2|在项目根目录下,执行以下命令
pip freeze > requirements.txt
在项目根目录下运行上述命令后,requrements.txt
文件将会生成在项目的根目录下。
方法 3:使用 PyCharm 的工具生成
使用这个方法生成的 requirements.txt
文件与使用 pipreqs
扫描项目代码生成的 requirements.txt
类似。
Step 1|在 PyCharm 中,点击 Tool > Sync Python Requirements
Step 2|使用默认配置生成即可