How To I List Imported Modules With Their Version?
I need to list all imported modules together with their version. Some of my code only works with specific versions and I want to save the version of the packages, so that I can loo
Solution 1:
Because you have a list of strings of the module name, not the module itself. Try this:
for module_name in modules:
    module = sys.modules[module_name]
    print module_name, getattr(module, '__version__', 'unknown')
Note that not all modules follow the convention of storing the version information in __version__. 
Solution 2:
One of the issues I have had with huge legacy programs is where aliases have been used (import thing as stuff). It is also often good to know exactly which file is being loaded. I wrote this module a while ago which might do what you need:
spection.py
"""
Python 2 version
10.1.14
"""import inspect
import sys
import re
deflook():
    for name, val in sys._getframe(1).f_locals.items():
        if inspect.ismodule(val):
            fullnm = str(val)
            ifnot'(built-in)'in fullnm and \
               not __name__     in fullnm:
                m = re.search(r"'(.+)'.*'(.+)'", fullnm)
                module,path = m.groups()
                print"%-12s maps to %s" % (name, path)
                ifhasattr(val, '__version__'):
                    print"version:", val.__version__
Using it:
import sys
import matplotlib
import spection
spection.look()
Gives (on my system):
matplotlib   maps to /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/__init__.pyc
version:1.3.1You will note that I omit builtins like sys and the spection module itself.
Post a Comment for "How To I List Imported Modules With Their Version?"