Gaudi Framework, version v23r6

Home   Generated: Wed Jan 30 2013
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
env.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 """
3 Small script to execute a command in a modified environment (see man 1 env).
4 """
5 import os
6 
7 class EnvError(RuntimeError):
8  '''
9  Simple class to wrap errors in the environment configuration.
10  '''
11  pass
12 
13 def splitNameValue(name_value):
14  """split the "NAME=VALUE" string into the tuple ("NAME", "VALUE")
15  replacing '[:]' with os.pathsep in VALUE"""
16  if '=' not in name_value:
17  raise EnvError("Invalid variable argument '%s'." % name_value)
18  n, v = name_value.split('=', 1)
19  return n, v.replace('[:]', os.pathsep)
20 
21 def parse_args():
22  '''
23  Parse the command line arguments.
24  '''
25 
26  from optparse import OptionParser, OptionValueError
27 
28  def addOperation(option, opt, value, parser, action):
29  '''
30  Append to the list of actions the tuple (action, (<args>, ...)).
31  '''
32  if action not in ('unset', 'loadXML'):
33  try:
34  value = splitNameValue(value)
35  except EnvError:
36  raise OptionValueError("Invalid value for option %s: '%s', it requires NAME=VALUE." % (opt, value))
37  else:
38  value = (value,)
39  parser.values.actions.append((action, value))
40 
41  parser = OptionParser(prog = "env.py",
42  usage = "Usage: %prog [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]",
43  description = "Set each NAME to VALUE in the environment and run COMMAND.",
44  epilog = "The operations are performed in the order they appear on the "
45  "command line. If no COMMAND is provided, print the resulting "
46  "environment. (Note: this command is modeled after the Unix "
47  "command 'env', see \"man env\")" )
48 
49  parser.add_option("-i", "--ignore-environment",
50  action="store_true",
51  help="start with an empty environment")
52  parser.add_option("-u", "--unset",
53  metavar="NAME",
54  action="callback", callback=addOperation,
55  type="str", nargs=1, callback_args=('unset',),
56  help="remove variable from the environment")
57  parser.add_option("-s", "--set",
58  metavar="NAME=VALUE",
59  action="callback", callback=addOperation,
60  type="str", nargs=1, callback_args=('set',),
61  help="set the variable NAME to VALUE")
62  parser.add_option("-a", "--append",
63  metavar="NAME=VALUE",
64  action="callback", callback=addOperation,
65  type="str", nargs=1, callback_args=('append',),
66  help="append VALUE to the variable NAME (with a '%s' as separator)" % os.pathsep)
67  parser.add_option("-p", "--prepend",
68  metavar="NAME=VALUE",
69  action="callback", callback=addOperation,
70  type="str", nargs=1, callback_args=('prepend',),
71  help="prepend VALUE to the variable NAME (with a '%s' as separator)" % os.pathsep)
72  parser.add_option("-x", "--xml",
73  action="callback", callback=addOperation,
74  type="str", nargs=1, callback_args=('loadXML',),
75  help="XML file describing the changes to the environment")
76  parser.add_option("--sh",
77  action="store_const", const="sh", dest="shell",
78  help="Print the environment as shell commands for 'sh'-derived shells.")
79  parser.add_option("--csh",
80  action="store_const", const="csh", dest="shell",
81  help="Print the environment as shell commands for 'csh'-derived shells.")
82  parser.add_option("--py",
83  action="store_const", const="py", dest="shell",
84  help="Print the environment as Python dictionary.")
85  parser.disable_interspersed_args()
86  parser.set_defaults(actions=[], ignore_environment=False)
87 
88  return parser.parse_args()
89 
90 def prepareEnv(ignore_system=False):
91  '''
92  Prepare an EnvConfig.Control instance to operate on the environment.
93 
94  @param ignore_system: if set to True, the system environment is ignored.
95  '''
96  from EnvConfig import Control
97  control = Control.Environment()
98 
99  if not ignore_system:
100  control.presetFromSystem()
101 
102  return control
103 
104 def makeEnv(actions, ignore_system=False):
105  '''
106  Return a dictionary of the environment variables after applying the actions.
107 
108  @param ignore_system: if set to True, the system environment is ignored.
109  '''
110  # prepare initial control object
111  control = prepareEnv(ignore_system)
112 
113  # apply all the actions
114  for action, args in actions:
115  apply(getattr(control, action), args)
116 
117  # extract the result env dictionary
118  return control.vars()
119 
120 def main():
121  '''
122  Main function of the script.
123  '''
124 
125  opts, args = parse_args()
126 
127  cmd = []
128  # find the (implicit) 'set' arguments in the list of arguments
129  # and put the rest in the command
130  try:
131  for i, a in enumerate(args):
132  opts.actions.append(('set', splitNameValue(a)))
133  except EnvError:
134  cmd = args[i:]
135 
136  if opts.shell and cmd:
137  print >> sys.stderr, "Invalid arguments: --%s cannot be used with a command." % opts.shell
138  return 2
139 
140  env = makeEnv(opts.actions, opts.ignore_environment)
141 
142  if "LD_LIBRARY_PATH" in env:
143  # replace LD_LIBRARY_PATH with the corresponding one on other systems
144  if sys.platform.startswith("win"):
145  other = "PATH"
146  elif sys.platform.startswith("darwin"):
147  other = "DYLD_LIBRARY_PATH"
148  else:
149  other = None
150  if other:
151  if other in env:
152  env[other] = env[other] + os.pathsep + env["LD_LIBRARY_PATH"]
153  else:
154  env[other] = env["LD_LIBRARY_PATH"]
155  del env["LD_LIBRARY_PATH"]
156 
157  if not cmd:
158  if opts.shell == 'py':
159  from pprint import pprint
160  pprint(env)
161  else:
162  template = {'sh': "export %s='%s'",
163  'csh': "setenv %s '%s'"}.get(opts.shell, "%s=%s")
164  for nv in sorted(env.items()):
165  print template % nv
166  return 0
167  else:
168  from subprocess import Popen
169  return Popen(cmd, env=env).wait()
170 
171 if __name__ == "__main__":
172  import sys
173  sys.exit(main())

Generated at Wed Jan 30 2013 17:13:37 for Gaudi Framework, version v23r6 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004