Browse Source

Generic module importer

master
Julio Biason 15 years ago
parent
commit
453f19dcf0
  1. 22
      mitterlib/__init__.py
  2. 29
      mitterlib/network/__init__.py

22
mitterlib/__init__.py

@ -17,6 +17,8 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os.path
import glob
import logging
@ -48,3 +50,23 @@ def find_image(image_name):
return filename
return None
def module_search(source, ignore):
"""Search for modules in the source directory. Ignore any modules
indicated."""
base_dir = os.path.dirname(source)
modules = glob.glob(os.path.join(base_dir, '*.py'))
for module in modules:
module_name = os.path.basename(module)
if module_name in ignore:
# not a usable module
continue
try:
module_name = _import_name(module_name)
yield module_name
except ImportError, exc:
_log.debug('Module %s is not "importable"', module_name)
_log.debug(str(exc))
pass

29
mitterlib/network/__init__.py

@ -17,11 +17,10 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os.path
import glob
import logging
from mitterlib.network.networkbase import NetworkData
from mitterlib import module_search
_log = logging.getLogger('mitterlib.network.Networks')
@ -34,23 +33,12 @@ SKIPPABLES = ('__init__.py', 'networkbase.py')
def _import_name(module):
"""Based on the name of the module, return the proper "import"
statement."""
(name, _) = os.path.splitext(module)
return 'mitterlib.network.%s' % (name)
def _networks():
network_dir = os.path.dirname(__file__)
networks = glob.glob(os.path.join(network_dir, '*.py'))
for network in networks:
network_name = os.path.basename(network)
if network_name in SKIPPABLES:
# not a real network
continue
module_name = _import_name(network_name)
yield module_name
#--------------------------------------------------------------------
# Exceptions
#--------------------------------------------------------------------
@ -102,13 +90,10 @@ class Networks(object):
if self._networks:
return self._networks
for module_name in _networks():
try:
module = __import__(module_name, fromlist=[module_name])
connection = module.Connection(self._options)
self._networks[connection.SHORTCUT] = connection
except ImportError, ex:
raise NetworksErrorLoadingNetwork(module_name, ex)
for module_name in module_search(__file__, SKIPPABLES):
module = __import__(module_name, fromlist=[module_name])
connection = module.Connection(self._options)
self._networks[connection.SHORTCUT] = connection
return self._networks

Loading…
Cancel
Save