Commits

oliver_g committed b179a9a Draft

allow specifying actual pathes in HACHOIR_PARSERS env var

If the full path is specified (rather than the module name), the loaded
package doesn't have to be in Python search path. This should make it easier
to use external parsers.

  • Participants
  • Parent commits 24120bf
  • Branches external-parsers2

Comments (0)

Files changed (1)

File hachoir-parser/hachoir_parser/parser_list.py

         if self.parser_list:
             return self.parser_list
 
-        parserModules = ["hachoir_parser"]
-        if os.environ.has_key('HACHOIR_PARSERS'):
-            parserModules += os.environ['HACHOIR_PARSERS'].split(':')
+        # load main parsers:
+        module = __import__("hachoir_parser")
+        self._loadModule(module)
 
-        for moduleName in parserModules:
-            if moduleName:
-                self._loadModule(moduleName)
+        # load optional external parsers:
+        if os.environ.has_key("HACHOIR_PARSERS"):
+            import imp
+            i = 0
+            for path in os.environ["HACHOIR_PARSERS"].split(":"):
+                try:
+                    # try to interpret path as actual module name:
+                    module = __import__(path)
+                except ImportError:
+                    # load module from specified path:
+                    try:
+                        (file, modPath, desc) = imp.find_module("", [path])
+                        module = imp.load_module("ext_hachoir_parser_%d" % i, file, modPath, desc)
+                    except ImportError, e:
+                        print "failed to load external parsers from '%s' (%s)" % (path, e)
+                        continue
+                self._loadModule(module)
+                i+=1
 
         assert 1 <= len(self.parser_list)
         return self.parser_list
 
-    def _loadModule(self, modName):
+    def _loadModule(self, module):
         todo = []
-        module = __import__(modName)
         for attrname in dir(module):
             attr = getattr(module, attrname)
             if isinstance(attr, types.ModuleType):