diff options
author | Josh Blum | 2013-07-27 01:17:46 -0700 |
---|---|---|
committer | Josh Blum | 2013-07-27 01:17:46 -0700 |
commit | 7a677f768094fecfbb04e7b803c99cc2787153a2 (patch) | |
tree | 347e4bd306307bd0f9c979518f840bab00da5488 /python/gras/GRAS_Loader.py | |
parent | b877d078b11cb848b344f4f7534398f70157aa15 (diff) | |
download | sandhi-7a677f768094fecfbb04e7b803c99cc2787153a2.tar.gz sandhi-7a677f768094fecfbb04e7b803c99cc2787153a2.tar.bz2 sandhi-7a677f768094fecfbb04e7b803c99cc2787153a2.zip |
gras: work on module loading and python factory
naming convention, path convention, env var convention,
And, make a python factory -- but its a little halfassed.
You see, we didnt do the swig director thing yet,
so C++ cant yet create python blocks from the factory.
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", ""), "") |