Salome HOME
PR: merge branch CCAR_br1
[modules/kernel.git] / src / SALOME_SWIG / salome_shared_modules.py
1 """
2 This module with help of import_hook and *_shared_modules
3 filters imports when using the embedded Python interpretor.
4
5 Some imports can't be done more than once.
6 This is related to the multi study feature that is implemented
7 by using the Python multi interpreter feature.
8 Some modules register objects or classes by calling modules
9 implemented in C. These operations can't be done multiple times.
10 So it's very important to control these imports.
11
12 Examples:
13   - PyQt : import qt calls a C module to register classes
14   - OmniORB : import *_idl calls a C module to register CORBA interfaces
15
16 Usage:
17   - First : the module salome_shared_modules is imported by main Python interpretor.
18     It will keep a dictionnary and a list that are shared among all
19     the subinterpretors and imports import_hook module that replaces
20     the standard import mechanism par one that prevents more than one import
21     for some modules identified by name (call register_name) or by a 
22     validator (call register_pattern).
23
24   Calls to register_name and register_pattern are done in modules named *_shared_modules
25   that could be found in the path SALOMEPATH
26
27 """
28 import glob,os,sys
29
30 import import_hook
31 # shared_imported, patterns, register_name, register_pattern
32 # will be shared by all Python sub interpretors
33 from import_hook import shared_imported
34 from import_hook import patterns
35 from import_hook import register_name
36 from import_hook import register_pattern
37
38 register_name("salome_shared_modules")
39
40 # Get the SALOMEPATH if set or else use KERNEL_ROOT_DIR that should be set.
41 salome_path=os.environ.get("SALOMEPATH",os.getenv("KERNEL_ROOT_DIR"))
42
43 list_modules=[]
44
45 # Import all *_shared_modules in the path and store them in list_modules
46 path=salome_path.split(":")
47 for rep in path:
48     # Import all *_shared_modules in rep
49     for f in glob.glob(os.path.join(rep,"lib","python"+sys.version[:3],"site-packages","salome","shared_modules","*_shared_modules.py")):
50         try:
51            m=__import__(os.path.splitext(os.path.basename(f))[0])
52            list_modules.append(m)
53         except:
54            pass
55
56
57 # If shared modules have been imported before installing import mechanism
58 # we add them to shared_imported
59 #
60 for name,module in sys.modules.items():
61     if import_hook.is_shared(name) and shared_imported.get(name) is None:
62        #print "Module shared added to shared_imported: ",name
63        shared_imported[name]=module
64