summaryrefslogtreecommitdiff
path: root/python/gras/GRAS_Loader.py
blob: cc73d9b91bd948c52e9da4bcd7b938dad85386b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Copyright (C) by Josh Blum. See LICENSE.txt for licensing information.

import os
import sys
import traceback

#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
        print traceback.format_exc()
    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", ""), "")