All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
EnvConfig.Script Class Reference
Inheritance diagram for EnvConfig.Script:
Collaboration diagram for EnvConfig.Script:

Public Member Functions

def __init__
 
def dump
 
def expandEnvVars
 
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 35 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 46 of file __init__.py.

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

Member Function Documentation

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

Definition at line 161 of file __init__.py.

162  def _check_args(self):
163  '''
164  Check consistency of command line options and arguments.
165  '''
166  if self.opts.shell and self.cmd:
167  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 168 of file __init__.py.

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

Definition at line 141 of file __init__.py.

142  def _parse_args(self, args=None):
143  '''
144  Parse the command line arguments.
145  '''
146  opts, args = self.parser.parse_args(args)
147 
148  # set the logging level
149  logging.basicConfig(level=opts.log_level)
150 
151  cmd = []
152  # find the (implicit) 'set' arguments in the list of arguments
153  # and put the rest in the command
154  try:
155  for i, a in enumerate(args):
156  opts.actions.append(('set', splitNameValue(a)))
157  except EnvError:
158  cmd = args[i:]
159 
160  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 62 of file __init__.py.

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

Definition at line 203 of file __init__.py.

204  def dump(self):
205  '''
206  Print to standard output the final environment in the required format.
207  '''
208  if self.opts.shell == 'py':
209  from pprint import pprint
210  pprint(self.env)
211  else:
212  template = {'sh': "export %s='%s'",
213  'csh': "setenv %s '%s'"}.get(self.opts.shell, "%s=%s")
214  for nv in sorted(self.env.items()):
215  print template % nv
def EnvConfig.Script.expandEnvVars (   self,
  iterable 
)
Return a copy of iterable where all the elements have the environment
variables expanded.

>>> s = Script([])
>>> s.env = {'A': '1', 'B': 'test'}
>>> s.expandEnvVars(['$A', '${B}-$A', '$DUMMY-$A', '$$B'])
['1', 'test-1', '$DUMMY-1', '$B']

Definition at line 216 of file __init__.py.

217  def expandEnvVars(self, iterable):
218  '''
219  Return a copy of iterable where all the elements have the environment
220  variables expanded.
221 
222  >>> s = Script([])
223  >>> s.env = {'A': '1', 'B': 'test'}
224  >>> s.expandEnvVars(['$A', '${B}-$A', '$DUMMY-$A', '$$B'])
225  ['1', 'test-1', '$DUMMY-1', '$B']
226  '''
227  return [Template(elem).safe_substitute(self.env) for elem in iterable]
def EnvConfig.Script.main (   self)
Main function of the script.

Definition at line 242 of file __init__.py.

243  def main(self):
244  '''
245  Main function of the script.
246  '''
247  self._makeEnv()
248  if not self.cmd:
249  self.dump()
250  else:
251  sys.exit(self.runCmd())
def EnvConfig.Script.runCmd (   self)
Execute a command in the modified environment and return the exit code.

Definition at line 228 of file __init__.py.

229  def runCmd(self):
230  '''
231  Execute a command in the modified environment and return the exit code.
232  '''
233  from subprocess import Popen
234  cmd = self.expandEnvVars(self.cmd)
235  rc = Popen(cmd, env=self.env).wait()
236  # There is a mismatch between Popen return code and sys.exit argument in
237  # case of signal.
238  # E.g. Popen returns -6 that is translated to 250 instead of 134
239  if rc < 0:
240  rc = 128 - rc
241  return rc

Member Data Documentation

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

Definition at line 41 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 42 of file __init__.py.

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

Definition at line 40 of file __init__.py.

EnvConfig.Script.cmd

Definition at line 53 of file __init__.py.

EnvConfig.Script.control

Definition at line 54 of file __init__.py.

EnvConfig.Script.env

Definition at line 56 of file __init__.py.

EnvConfig.Script.log

Definition at line 55 of file __init__.py.

EnvConfig.Script.opts

Definition at line 52 of file __init__.py.

EnvConfig.Script.parser

Definition at line 51 of file __init__.py.


The documentation for this class was generated from the following file: