creating a list of all imported modules
John Machin
sjmachin at lexicon.net
Tue Mar 10 06:43:08 EDT 2009
On Mar 10, 11:01 am, Tim Michelsen <timmichel... at gmx-topmail.de>
wrote:
> Hello,
>
> how do I create a list of all modules imported by my module/script and
> which are present in the namespace?
>
> I am looking for something like %who in Ipython.
>
> My aim is to create a file for the documentation that shows all
> dependencies of my script on external (3rd party) libraries.
To sort out which imported modules are supplied by Python, by you, and
by 3rd parties it would help a lot if you knew where the modules are
being loaded from.
Put this code at the end of your script:
import sys
info = [(module.__file__, name)
for (name, module) in sys.modules.iteritems()
if hasattr(module, '__file__')]
info.sort()
import pprint
pprint.pprint(info)
AFAIK unless someone has been messing with sys.modules, this gives you
all modules that have been imported during the running of your script,
except for built-ins (no __file__ attribute). Warning: I've not tried
this with eggs and zips.
HTH,
John
More information about the Python-list
mailing list