2

I have a (Django) project with lots of imports that I started without virtualenv. Is there a way to

pip freeze

only the Python packages that are actually imported somewhere in the project, i.e. they are required by my project?

pip freeze

would list all the packages installed in my system, but I would only need those ones that are used by my project.

Botond
  • 2,640
  • 6
  • 28
  • 44
  • Possible duplicate of [How to list imported modules?](http://stackoverflow.com/questions/4858100/how-to-list-imported-modules) – JamesD Nov 03 '16 at 11:19
  • you can start with `grep -r 'import' ./` – Fi3 Nov 03 '16 at 12:34
  • @Fi3: the problem is that this won't give exact package names with version numbers – Botond Nov 03 '16 at 13:17
  • 2
    Have a look at [pipreqs](https://github.com/bndr/pipreqs). Also, not what you're looking for here, but you may like [pip-tools](https://github.com/nvie/pip-tools), as well. – jonafato Nov 03 '16 at 14:08
  • @jonafato: pipreqs looks interesting. It seems to miss lots of packages though... For me, if I navigate to every subdirectory, it would find the imports, but will miss some of them when running from the project root. – Botond Nov 03 '16 at 15:35

1 Answers1

2

A manual solution could be

Find the packages with grep

grep -r import ./*/*[.py] > j.t

Iterate all the lines in j.t with python

fromIndex = line.find('from')
importIndex = line.find('import')
if fromIndex != -1:
    return = line[fromIndex + 5 : importIndex - 1][5:]
else:
    return = line[importIndex + 7:]

Remove all the duplicates

Pip freeze in the virtual env for find the version number

Pip freeze out the virtual env for find the other version number

Fi3
  • 429
  • 6
  • 17