views:

100

answers:

4

How can I get a list of the modules that have been imported into my process?

+4  A: 
import sys
print sys.modules.keys()
Forest
+8  A: 

sys.modules.values() ... if you really need the names of the modules, use sys.modules.keys()

dir() is not what you want.

>>> import re
>>> def foo():
...     import csv
...     fubar = 0
...     print dir()
...
>>> foo()
['csv', 'fubar'] # 're' is not in the current scope
>>>
John Machin
+3  A: 

You can also run the interpreter with -v option if you just want to see the modules that are imported (and the order they are imported in)

gnibbler
A: 

You could very simply do this (without having to import sys):

dir()

This will tell you all the modules that you can call without having to import (i.e. the modules that you've imported thus far). However, you could find things like __ builtins__ here as well. So if you want to see only those entries that don't have the underscores, then you can do something like this:

things_that_i_have_imported = [i for i in dir() if "_" not in i]

However, beware that doing this will not show you a module like _happy even if you have imported it. So if you want to filter out strictly those modules with leading an trailing underscores, then you can do:

things_that_i_have_imported = [i for i in dir() if i[0:2] != "_" != i[-2:]]

But this gets more into string manipulation, which you can also do by regex

Hope this helps

inspectorG4dget
-1 `dir()` returns a list of names *in the current scope*. It will certainly contain the names of modules that have been imported into the current scope, but it will also contain names of any non-modules. Futzing with underscores doesn't seem useful.
John Machin