Crombie Tools
LoadConfig.py
Go to the documentation of this file.
1 """ @file LoadConfig.py
2 Defines the CrombieTools.LoadConfig package
3 @author Daniel Abercrombie <dabercro@mit.edu>
4 
5 @package CrombieTools.LoadConfig
6 Package that loads local [configuration files](@ref envconfig) into environment.
7 """
8 
9 import os
10 import subprocess
11 
12 
13 def LoadEnv(configs):
14  """Sources bash files and loads the resulting environment into os.environ
15 
16  @param configs is a list of file names that should be searched for.
17  A string for a single configuration file is also accepted.
18  """
19  if type(configs) == str:
20  LoadEnv([configs])
21  elif type(configs) == list:
22  for config in configs:
23  if os.path.exists(config):
24  configContents = subprocess.Popen(['bash','-c','source ' + config + '; env'],
25  stdout = subprocess.PIPE)
26  for line in configContents.stdout:
27  if type(line) == bytes:
28  (key,sep,value) = line.decode('utf-8').partition('=')
29  elif type(line) == str:
30  (key,sep,value) = line.partition('=')
31  else:
32  print('Not sure how to handle subprocess output. Contact Dan.')
33  break
34  os.environ[str(key)] = str(value).strip('\n')
35 
36  configContents.communicate()
37  else:
38  print 'You passed an invalid argument type to CrombieTools.LoadConfig.LoadEnv()'
39  exit()
40 
41 
42 def LoadModuleFromEnv(EnvVarName):
43  """Loads and returns a python file named in the environment as a module.
44 
45  @param EnvVarName is an environment variable containing the name of a local .py file.
46  @returns the module handler from importing the .py file.
47  """
48  if not os.environ.get(EnvVarName) == None:
49  if os.path.exists(os.environ[EnvVarName]):
50  return __import__(os.environ[EnvVarName].strip('.py'), globals(), locals(), [], -1)
51  return None
52 
53 
54 """List of configuration files that this module tries to load automatically."""
55 CrombieConfigs = ['CrombieAnalysisConfig.sh','CrombiePlotterConfig.sh','CrombieSlimmingConfig.sh']
56 
57 LoadEnv(CrombieConfigs)
58 
59 """ Sub module set by the [$CrombieCutsFile](@ref envconfig) environment variable."""
60 cuts = LoadModuleFromEnv('CrombieCutsFile')