import question
Yigal Duppen
yduppen at chello.nl
Tue May 14 14:58:53 EDT 2002
> Hi all,
>
> Is there a way to import all possible Python-modules in a module with
> a single call (or some other small elegant solution)?
Warning: horrible code ahead!
Warning2: this code is not meant for serious use; the other posters have
given far better alternatives.
Yes, it is possible to import all possible python-modules using a mere two
lines. This is what I made of it:
import sys, re, os, os.path, operator
for m in map(lambda name: os.path.splitext(name)[0], filter(lambda name:
re.match(r"^.*?\.py.?$", name), reduce(operator.add, map(os.listdir,
filter(None, sys.path))))): globals()[m] = __import__(m)
Disected, it does the following:
1) get all directories in sys.path
filter(None, sys.path)
2) get all the entries in those directories
map(os.listdir, ...)
this results in a list of lists of files
3) turn this into one huge list:
reduce(operator.add, ...)
4) keep only the python files (those ending with .py, .pyc or .pyo)
this is done by matching against the regular expression r"^.*?\.py.?$"
filter(lambda name: re.match(r"^.*?\.py.?$", name), ...)
5) remove the extensions
filter(lambda name: os.path.splitext(name)[0], ...)
You now have a list of the names of all modules you can normally load.
These can be imported by using
for m in ...: globals()[m] = __import__(m)
YDD
--
.sigmentation fault
More information about the Python-list
mailing list