Gaudi Framework, version v25r0

Home   Generated: Mon Feb 17 2014
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
Public Member Functions | Public Attributes | Private Member Functions | Static Private Attributes | List of all members
EnvConfig.Script Class Reference
Inheritance diagram for EnvConfig.Script:
Inheritance graph
[legend]
Collaboration diagram for EnvConfig.Script:
Collaboration graph
[legend]

Public Member Functions

def __init__
 
def dump
 
def runCmd
 
def main
 

Public Attributes

 parser
 
 opts
 
 cmd
 
 control
 
 log
 
 env
 

Private Member Functions

def _prepare_parser
 
def _parse_args
 
def _check_args
 
def _makeEnv
 

Static Private Attributes

string __usage__ "Usage: %prog [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]"
 
string __desc__ "Set each NAME to VALUE in the environment and run COMMAND."
 
tuple __epilog__
 

Detailed Description

Environment Script class used to control the logic of the script and allow
extensions.

Definition at line 32 of file __init__.py.

Constructor & Destructor Documentation

def EnvConfig.Script.__init__ (   self,
  args = None 
)
Initializes the script instance parsing the command line arguments (or
the explicit arguments provided).

Definition at line 43 of file __init__.py.

43 
44  def __init__(self, args=None):
45  '''
46  Initializes the script instance parsing the command line arguments (or
47  the explicit arguments provided).
48  '''
49  self.parser = None
50  self.opts = None
51  self.cmd = None
52  self.control = None
53  self.log = None
54  self.env = {}
55  # Run the core code of the script
56  self._prepare_parser()
57  self._parse_args(args)
58  self._check_args()

Member Function Documentation

def EnvConfig.Script._check_args (   self)
private
Check consistency of command line options and arguments.

Definition at line 158 of file __init__.py.

159  def _check_args(self):
160  '''
161  Check consistency of command line options and arguments.
162  '''
163  if self.opts.shell and self.cmd:
164  self.parser.error("Invalid arguments: --%s cannot be used with a command." % self.opts.shell)
def EnvConfig.Script._makeEnv (   self)
private
Generate a dictionary of the environment variables after applying all
the required actions.

Definition at line 165 of file __init__.py.

166  def _makeEnv(self):
167  '''
168  Generate a dictionary of the environment variables after applying all
169  the required actions.
170  '''
171  # prepare the environment control instance
172  control = Control.Environment()
173  if not self.opts.ignore_environment:
174  control.presetFromSystem()
175 
176  # apply all the actions
177  for action, args in self.opts.actions:
178  apply(getattr(control, action), args)
179 
180  # extract the result env dictionary
181  env = control.vars()
182 
183  # set the library search path correctly for the non-Linux platforms
184  if "LD_LIBRARY_PATH" in env:
185  # replace LD_LIBRARY_PATH with the corresponding one on other systems
186  if sys.platform.startswith("win"):
187  other = "PATH"
188  elif sys.platform.startswith("darwin"):
189  other = "DYLD_LIBRARY_PATH"
190  else:
191  other = None
192  if other:
193  if other in env:
194  env[other] = env[other] + os.pathsep + env["LD_LIBRARY_PATH"]
195  else:
196  env[other] = env["LD_LIBRARY_PATH"]
197  del env["LD_LIBRARY_PATH"]
198 
199  self.env = env
def EnvConfig.Script._parse_args (   self,
  args = None 
)
private
Parse the command line arguments.

Definition at line 138 of file __init__.py.

139  def _parse_args(self, args=None):
140  '''
141  Parse the command line arguments.
142  '''
143  opts, args = self.parser.parse_args(args)
144 
145  # set the logging level
146  logging.basicConfig(level=opts.log_level)
147 
148  cmd = []
149  # find the (implicit) 'set' arguments in the list of arguments
150  # and put the rest in the command
151  try:
152  for i, a in enumerate(args):
153  opts.actions.append(('set', splitNameValue(a)))
154  except EnvError:
155  cmd = args[i:]
156 
157  self.opts, self.cmd = opts, cmd
def EnvConfig.Script._prepare_parser (   self)
private
Prepare an OptionParser instance used to analyze the command line
options and arguments.

Definition at line 59 of file __init__.py.

59 
60  def _prepare_parser(self):
61  '''
62  Prepare an OptionParser instance used to analyze the command line
63  options and arguments.
64  '''
65  from optparse import OptionParser, OptionValueError
66  parser = OptionParser(prog=os.path.basename(sys.argv[0]),
67  usage=self.__usage__,
68  description=self.__desc__,
69  epilog=self.__epilog__)
70  self.log = logging.getLogger(parser.prog)
71 
72  def addOperation(option, opt, value, parser, action):
73  '''
74  Append to the list of actions the tuple (action, (<args>, ...)).
75  '''
76  if action not in ('unset', 'loadXML'):
77  try:
78  value = splitNameValue(value)
79  except EnvError:
80  raise OptionValueError("Invalid value for option %s: '%s', it requires NAME=VALUE." % (opt, value))
81  else:
82  value = (value,)
83  parser.values.actions.append((action, value))
84 
85  parser.add_option("-i", "--ignore-environment",
86  action="store_true",
87  help="start with an empty environment")
88  parser.add_option("-u", "--unset",
89  metavar="NAME",
90  action="callback", callback=addOperation,
91  type="str", nargs=1, callback_args=('unset',),
92  help="remove variable from the environment")
93  parser.add_option("-s", "--set",
94  metavar="NAME=VALUE",
95  action="callback", callback=addOperation,
96  type="str", nargs=1, callback_args=('set',),
97  help="set the variable NAME to VALUE")
98  parser.add_option("-a", "--append",
99  metavar="NAME=VALUE",
100  action="callback", callback=addOperation,
101  type="str", nargs=1, callback_args=('append',),
102  help="append VALUE to the variable NAME (with a '%s' as separator)" % os.pathsep)
103  parser.add_option("-p", "--prepend",
104  metavar="NAME=VALUE",
105  action="callback", callback=addOperation,
106  type="str", nargs=1, callback_args=('prepend',),
107  help="prepend VALUE to the variable NAME (with a '%s' as separator)" % os.pathsep)
108  parser.add_option("-x", "--xml",
109  action="callback", callback=addOperation,
110  type="str", nargs=1, callback_args=('loadXML',),
111  help="XML file describing the changes to the environment")
112  parser.add_option("--sh",
113  action="store_const", const="sh", dest="shell",
114  help="Print the environment as shell commands for 'sh'-derived shells.")
115  parser.add_option("--csh",
116  action="store_const", const="csh", dest="shell",
117  help="Print the environment as shell commands for 'csh'-derived shells.")
118  parser.add_option("--py",
119  action="store_const", const="py", dest="shell",
120  help="Print the environment as Python dictionary.")
121 
122  parser.add_option('--verbose', action='store_const',
123  const=logging.INFO, dest='log_level',
124  help='print more information')
125  parser.add_option('--debug', action='store_const',
126  const=logging.DEBUG, dest='log_level',
127  help='print debug messages')
128  parser.add_option('--quiet', action='store_const',
129  const=logging.WARNING, dest='log_level',
130  help='print only warning messages (default)')
131 
132  parser.disable_interspersed_args()
133  parser.set_defaults(actions=[],
134  ignore_environment=False,
135  log_level=logging.WARNING)
136 
137  self.parser = parser
def EnvConfig.Script.dump (   self)
Print to standard output the final environment in the required format.

Definition at line 200 of file __init__.py.

201  def dump(self):
202  '''
203  Print to standard output the final environment in the required format.
204  '''
205  if self.opts.shell == 'py':
206  from pprint import pprint
207  pprint(self.env)
208  else:
209  template = {'sh': "export %s='%s'",
210  'csh': "setenv %s '%s'"}.get(self.opts.shell, "%s=%s")
211  for nv in sorted(self.env.items()):
212  print template % nv
def EnvConfig.Script.main (   self)
Main function of the script.

Definition at line 220 of file __init__.py.

221  def main(self):
222  '''
223  Main function of the script.
224  '''
225  self._makeEnv()
226  if not self.cmd:
227  self.dump()
228  else:
229  sys.exit(self.runCmd())
def EnvConfig.Script.runCmd (   self)
Execute a command in the modified environment and return the exit code.

Definition at line 213 of file __init__.py.

214  def runCmd(self):
215  '''
216  Execute a command in the modified environment and return the exit code.
217  '''
218  from subprocess import Popen
219  return Popen(self.cmd, env=self.env).wait()

Member Data Documentation

string EnvConfig.Script.__desc__ "Set each NAME to VALUE in the environment and run COMMAND."
staticprivate

Definition at line 38 of file __init__.py.

tuple EnvConfig.Script.__epilog__
staticprivate
Initial value:
1 ("The operations are performed in the order they appear on the "
2  "command line. If no COMMAND is provided, print the resulting "
3  "environment. (Note: this command is modeled after the Unix "
4  "command 'env', see \"man env\")")

Definition at line 39 of file __init__.py.

string EnvConfig.Script.__usage__ "Usage: %prog [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]"
staticprivate

Definition at line 37 of file __init__.py.

EnvConfig.Script.cmd

Definition at line 50 of file __init__.py.

EnvConfig.Script.control

Definition at line 51 of file __init__.py.

EnvConfig.Script.env

Definition at line 53 of file __init__.py.

EnvConfig.Script.log

Definition at line 52 of file __init__.py.

EnvConfig.Script.opts

Definition at line 49 of file __init__.py.

EnvConfig.Script.parser

Definition at line 48 of file __init__.py.


The documentation for this class was generated from the following file:
Generated at Mon Feb 17 2014 14:38:14 for Gaudi Framework, version v25r0 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004