从需求文件中删除未使用的包 [英] Delete unused packages from requirements file
问题描述
有没有什么简单的方法可以从需求文件中删除不再使用的包?
Is there any easy way to delete no-more-using packages from requirements file?
我为此任务编写了一个 bash 脚本,但是它没有按我预期的那样工作.因为,有些包没有跟在它们的 PyPI 项目名称之后使用.例如;
I wrote a bash script for this task but, it doesn't work as I expected. Because, some packages are not used following their PyPI project names. For example;
dj-database-url
包用作
dj_database_url
我的项目在它自己的需求文件中有很多包,所以,一个一个地搜索它们太混乱、容易出错并且花费太多时间.正如我所搜索的,IDE 还没有这个属性.
My project has many packages in its own requirements file, so, searching them one-by-one is too messy, error-prone and takes too much time. As I searched, IDEs don't have this property, yet.
推荐答案
您可以在 PyCharm一>.
- 删除
requirements.txt
的内容,但保留空文件. - 加载您的项目,
- PyCharm 转到
Code ->检查代码...
. - 在对话框中选择
Whole project
选项并点击OK
.在检查结果面板中,找到Python
下的Package requirements
部分(注意只有当有任何requirements.txt
或时才会显示此部分>setup.py
文件).该部分将包含以下消息之一:
- Delete the contents of your
requirements.txt
but keep the empty file. - Load your project in,
- PyCharm go to
Code -> Inspect code...
. - Choose
Whole project
option in dialog and clickOK
. In inspection results panel locatePackage requirements
section underPython
(note that this section will be showed only if there is anyrequirements.txt
orsetup.py
file). The section will contain one of the following messages:
包装要求 '
.'如果 requirements.txt
中列出了任何包,但没有在任何 .py 文件中使用,则不满足包 '
中列出.'如果在 .py 文件中使用了任何包,但未在 requirements.txt
中列出,则不会在项目需求Package requirement '<package>' is not satisfied
if there is any package that is listed inrequirements.txt
but not used in any .py file.Package '<package>' is not listed in project requirements
if there is any package that is used in .py files, but not listed inrequirements.txt
.
您对第二次检查感兴趣.您可以通过右键单击 Package requirements
部分并选择 Apply Fix 'Add requirements '
.请注意,它只会显示一个包名称,但如果调用部分,它实际上会将所有使用的包添加到 requirements.txt
到requirements.txt'requirements.txt
.
You are interested in the second inspection.
You can add all used packages to requirements.txt
by right clicking the Package requirements
section and selecting Apply Fix 'Add requirements '<package>' to requirements.txt'
. Note that it will show only one package name, but it will actually add all used packages to requirements.txt
if called for section.
如果需要,可以一一添加,只需右键单击某个包对应的检查并选择Apply Fix 'Add requirements'
,重复这种检查.
If you want, you can add them one by one, just right click the inspection corresponding to certain package and choose Apply Fix 'Add requirements '<package>' to requirements.txt'
, repeat for each inspection of this kind.
之后,您可以创建干净的虚拟环境并从新的 requirements.txt
安装包.
After that you can create clean virtual environment and install packages from new requirements.txt
.
另请注意,PyCharm 具有导入优化功能,请参阅优化导入....在上面列出的任何其他步骤之前使用此功能会很有用.
Also note that PyCharm has import optimisation feature, see Optimize imports.... It can be useful to use this feature before any other steps listed above.
这篇关于从需求文件中删除未使用的包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!