diff options
Diffstat (limited to 'python/gras/GRAS_Loader.py')
-rw-r--r-- | python/gras/GRAS_Loader.py | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/python/gras/GRAS_Loader.py b/python/gras/GRAS_Loader.py new file mode 100644 index 0000000..b70bc60 --- /dev/null +++ b/python/gras/GRAS_Loader.py @@ -0,0 +1,48 @@ +# Copyright (C) by Josh Blum. See LICENSE.txt for licensing information. + +import os +import sys + +#try to import module +#http://effbot.org/zone/import-string.htm +def __try_module_import(filename): + directory, module_name = os.path.split(filename) + module_name = os.path.splitext(module_name)[0] + + path = list(sys.path) + sys.path.insert(0, directory) + try: + module = __import__(module_name) + except Exception as ex: + print 'Could not import', filename, ex + finally: + sys.path[:] = path # restore + +#recursive search for modules in path +def __module_import(p): + if not os.path.exists(p): return + if os.path.isfile(p): + return __try_module_import(p) + if not os.path.isdir(p): return + if os.path.exists(os.path.join(p, '__init__.py')): + return __try_module_import(p) + for sub in os.listdir(p): + name, ext = os.path.splitext(sub) + #prefer .pyo over .pyc, prefer .pyc over .py + has_pyc = os.path.exists(os.path.join(p, name+'.pyc')) + has_pyo = os.path.exists(os.path.join(p, name+'.pyo')) + if ext == ".py" and (has_pyc or has_pyo): continue + if ext == ".pyc" and has_pyo: continue + __module_import(os.path.join(p, sub)) + +#separate the paths and load each one +def __load_modules_from_paths(paths, suffix): + if not paths: return + for path in paths.split(os.pathsep): + if not path: continue + if suffix: path = os.path.join(path, suffix) + __module_import(path) + +__load_modules_from_paths(os.getenv("GRAS_ROOT", "@GRAS_ROOT@"), os.path.join("lib@LIB_SUFFIX@", "gras", "python")) +__load_modules_from_paths(os.getenv("GRAS_PATH", ""), os.path.join("lib@LIB_SUFFIX@", "gras", "python")) +__load_modules_from_paths(os.getenv("GRAS_PYTHON_PATH", ""), "") |