Reputation: 23
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 look it up again in the future. Listing the names of the packages works:
modules = list(set(sys.modules) & set(globals()))
print modules
But if I now want to get the version of the list items it doesn't work with:
for module in modules:
print module.__version__
Is there a way to address the .__version__
command with a string, or have I to go another way to get the name and the version?
In other questions only the names of the modules are addressed: How to list imported modules?
Upvotes: 2
Views: 5799
Reputation: 44344
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
def look():
for name, val in sys._getframe(1).f_locals.items():
if inspect.ismodule(val):
fullnm = str(val)
if not '(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)
if hasattr(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.1
You will note that I omit builtins like sys
and the spection module itself.
Upvotes: 3
Reputation: 362458
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__
.
Upvotes: 7