mrv
Covered: 26 lines
Missed: 100 lines
Skipped 85 lines
Percent: 20 %
  2
"""
  3
Initialize mrv system assisting development, debugging and maintenance
  5
	- install general `decorator` into __builtin__ namespace
  6
"""
  7
import __builtin__
  8
import logging
  9
import logging.config
 10
log = logging.getLogger("mrv")
 12
__all__ = ("init_modules", )
 15
import os, sys
 16
from path import Path
 20
def init_modules( filepath, moduleprefix, recurse=False, self_module = None):
 21
	""" Call '__initialize' functions in submodules of module at filepath if they exist
 22
	These functions should setup the module to be ready for work, its a callback informing
 23
	the submodules that the super module is being requested. They return a True value if
 24
	the initialization was performed, or a False one if they weren't for some reason.
 25
	Throw to indicate error.
 26
	:param filepath: your module module.__file__ value
 27
	:param moduleprefix: prefix like "super.yourmodule." leading to the submodules from
 28
	an available system include path
 29
	:param recurse: if True, method will recursively initialize submodules
 30
	:param self_module: if not None, it must be the module that called this function.
 31
	It will be given to the __initialize functions as first arguments allowing 
 32
	them to operate on functions of their own module - importing their own 
 33
	module is not yet possible as it is in the course of being intialized itself.
 34
	The module will be given only to intermediate submodules in case recurse is True.
 35
	:note: in this moment, all submodules will be 'pulled' in"""
 36
	moduledir = Path( filepath  ).parent()
 37
	moduleitems = moduledir.listdir( )
 38
	moduleitems.sort()					# assure we have the same order on every system
 39
	extensions = ( ".py", ".pyc", ".pyo" )
 40
	initialized_modules = set()
 42
	if not moduleprefix.endswith( "." ):
 43
		moduleprefix += "."
 46
	for path in moduleitems:
 49
		if path.isdir( ):
 50
			if not recurse:
 51
				continue
 53
			packageinitfile = None
 54
			for ext in extensions:
 55
				testpackageinitfile = path / "__init__%s" % ext
 56
				if testpackageinitfile.exists():
 57
					packageinitfile = testpackageinitfile
 58
					break
 63
			if not packageinitfile:
 64
				continue
 66
			init_modules( packageinitfile, moduleprefix + path.basename(), recurse=True )
 67
			continue
 70
		if path.ext() not in extensions:
 71
			continue
 73
		modulename = path.namebase()
 74
		if modulename.startswith( "_" ) or modulename.startswith( "." ) or modulename in ('all', 'mdb'):
 75
			continue
 77
		fullModuleName = moduleprefix + modulename
 78
		if fullModuleName in initialized_modules:
 79
			continue
 81
		initialized_modules.add(fullModuleName)
 82
		module = __import__( fullModuleName , globals(), locals(), [ modulename ] )
 85
		args = ( self_module and [ self_module ] ) or tuple()
 86
		if hasattr( module, "__initialize" ):
 87
			res = module.__initialize( *args )
 88
			if res:
 89
				log.info("Initialized " + module.__name__)
 98
def _remove_empty_syspath_entries():
 99
	"""fix sys.path: if there are empty entries and our cwd is the mrvroot
100
	we will be in trouble as we try to import our own 'maya' module which 
101
	will not provide the original maya packages of course
103
	:note: only for internal use - code was moved into a method as it needs 
104
		to be called again from maya.__init__"""
105
	while '' in sys.path:
106
		sys.path.remove('')
109
def _init_syspath( ):
110
	""" Initialize the path such that additional modules can be found"""
111
	import site
112
	mrvroot = mrvroot = os.path.dirname( __file__ )
114
	_remove_empty_syspath_entries()
121
	for syspath in sys.path[:]:
122
		if syspath.endswith('site-packages'):
123
			site.addsitedir(syspath, set(sys.path))
127
	if sys.platform == 'darwin':
130
		sys.path.append("/System/Library/Frameworks/Python.framework/Versions/%s/Extras/lib/python"%sys.version[:3])
134
	extbase = os.path.join( mrvroot, "ext" )
137
	pyparsing = os.path.join( extbase, "pyparsing", "src" )
140
	pydot = os.path.join( extbase, "pydot" )
143
	networkxpath = os.path.join( extbase, "networkx" )
146
	sys.path.append( pyparsing )
147
	sys.path.append( pydot )
148
	sys.path.append( networkxpath )
154
def _init_configProvider( ):
155
	""" Install the configuration provider system
157
	This allows values and settings to be stored in a convenient way. """
158
	pass
160
def _init_internationalization( ):
161
	"""Install internationalization module
163
	Using the default python gettext module, internationalization compatibility
164
	can be garantueed.
166
	Will map the '_' function to translate enclosed strings """
167
	import gettext
168
	gettext.install( "mrv" )
171
def _init_logging( ):
172
	""" Initialize the default mrv logging interface
174
	The logging interface unifies the way messages for the end user are handled
175
	and assure a flexible message handling.
177
	:note: will not raise even if the logging module could not be setup
179
	:note: in the current implementation, it is based on the default python logging
180
		package"""
181
	logcfgfile = os.environ.get('MRV_LOGGING_INI', None)
182
	if logcfgfile is None:
183
		return
185
	try:
186
		logcfgfile = Path(logcfgfile).expand_or_raise()
187
		logging.config.fileConfig(logcfgfile)
188
	except Exception, e:
189
		print "Failed to apply logging configuration at %s with error: %s" % (logcfgfile, str(e))
190
	else:
191
		log.debug("Initialized logging configuration from file at %s" % logcfgfile)
196
def _init_python( ):
197
	"""
198
	Assure that certain python classes have the least possible amount of compatablity
199
	so that we can work with them
200
	"""
207
_init_syspath( )
208
_init_configProvider( )
209
_init_internationalization( )
210
_init_logging( )
211
_init_python( )