Reputation: 4757
In my script, I imported 5 external modules this way :
import numpy as np
import scipy.io as sio
import pandas
import IPython
from termcolor import cprint
I want to get a complete list of external modules and versions imported above, so I wrote the following script :
def imports():
modulesList = []
for name, val in globals().items():
if isinstance(val, types.ModuleType):
modulesList.append(val.__name__)
return modulesList
import pip
installed_packages = sorted([ i.key for i in pip.get_installed_distributions() ])
modules = sorted(imports())
for module_name in modules:
module = sys.modules[module_name]
if module_name.lower() in installed_packages :
try : moduleVersion = module.__version__
except : moduleVersion = '.'.join( map(str, module.VERSION) )
print( "=> Imported %s version %s" % (module_name , moduleVersion) )
If I run this script, python shows :
=> Imported IPython version 6.0.0
=> Imported numpy version 1.13.1
=> Imported pandas version 0.20.2
instead of what I expect, which is the following :
=> Imported IPython version 6.0.0
=> Imported numpy version 1.13.1
=> Imported pandas version 0.20.2
=> Imported scipy version 0.19.0
=> Imported termcolor version 1.1.0
Can you help ?
Upvotes: 2
Views: 951
Reputation: 1158
So two things I determined from running your code. IPython isn't getting matched because of the line:
if module_name in installed_packages :
The installed_packages shows it as 'ipython' while you are checking for 'IPython'.
The second thing is the line:
modules = sorted(imports())
I'm not sure why but termcolor doesn't show up with
from termcolor import cprint
but does with
import termcolor
Not entirely sure what to make of that.
EDIT:
def imports():
modulesList = []
for name, val in globals().items():
if isinstance(val, types.ModuleType):
modulesList.append(val.__name__)
elif isinstance(val, types.FunctionType):
modulesList.append(sys.modules[val.__module__].__name__)
return modulesList
That should get you termcolor.
Upvotes: 1