You can use Code Inspection in PyCharm.
- Delete the contents of your
requirements.txtbut keep the empty file. - Load your project in,
- PyCharm go to
Code -> Inspect code.... - Choose
Whole projectoption in dialog and clickOK.
In inspection results panel locatePackage requirementssection underPython(note that this section will be showed only if there is anyrequirements.txtorsetup.pyfile).
The section will contain one of the following messages:
Package requirement '<package>' is not satisfiedif there is any package that is listed inrequirements.txtbut not used in any .py file.Package '<package>' is not listed in project requirementsif there is any package that is used in .py files, but not listed inrequirements.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.
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.
After that you can create clean virtual environment and install packages from new requirements.txt.
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.
