I would like to get a list of Python modules, which are in my Python installation (UNIX server).
How can you get a list of Python modules installed in your computer?
I would like to get a list of Python modules, which are in my Python installation (UNIX server).
How can you get a list of Python modules installed in your computer?
Now, these methods I tried myself, and I got exactly what was advertised: All the modules.
Alas, really you don't care much about the stdlib, you know what you get with a python install.
Really, I want the stuff that I installed.
What actually, surprisingly, worked just fine was:
Which returned:
I say "surprisingly" because the package install tool is the exact place one would expect to find this functionality, although not under the name 'freeze' but python packaging is so weird, that I am flabbergasted that this tool makes sense. Pip 0.8.2, Python 2.7.
This solution is primary based on modules
importlib
andpkgutil
and work with CPython 3.4 and CPython 3.5, but has no support for the CPython 2.Explanation
sys.builtin_module_names
- names all built-in modules (look my answer here)pkgutil.iter_modules()
- returns an information about all available modulesimportlib.util.find_spec()
- returns an information about importing module, if existsBuiltinImporter
- an importer for built-in modules (docs)SourceFileLoader
- an importer for a standard Python module (by default has extension *.py) (docs)ExtensionFileLoader
- an importer for modules as shared library (written on the C or C++)Full code
Usage
For the CPython3.5 (truncated)
For the CPython3.4 (truncated)
pip freeze does it all finding packages however one can simply write the following command to list all paths where python packages are.
In normal shell just use
Solution
My 50 cents for getting a
pip freeze
-like list from a Python script:As a (too long) one liner:
Giving:
Scope
This solution applies to the system scope or to a virtual environment scope, and covers packages installed by
setuptools
,pip
and (god forbid)easy_install
.My use case
I added the result of this call to my flask server, so when I call it with
http://example.com/exampleServer/environment
I get the list of packages installed on the server's virtualenv. It makes debugging a whole lot easier.Caveats
I have noticed a strange behaviour of this technique - when the Python interpreter is invoked in the same directory as a
setup.py
file, it does not list the package installed bysetup.py
.Steps to reproduce:
Create a virtual environment Clone a git repo withsetup.py
We have behave's
Install the python package from the git reposetup.py
in/tmp/behave
:If we run the aforementioned solution from
/tmp
If we run the aforementioned solution from
/tmp/behave
behave==1.2.5a1
is missing from the second example, because the working directory containsbehave
'ssetup.py
file.I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.
in a Python shell/prompt.