3 Small script to execute a command in a modified environment (see man 1 env).
9 Simple class to wrap errors in the environment configuration.
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)
23 Parse the command line arguments.
26 from optparse
import OptionParser, OptionValueError
28 def addOperation(option, opt, value, parser, action):
30 Append to the list of actions the tuple (action, (<args>, ...)).
32 if action
not in (
'unset',
'loadXML'):
36 raise OptionValueError(
"Invalid value for option %s: '%s', it requires NAME=VALUE." % (opt, value))
39 parser.values.actions.append((action, value))
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\")" )
49 parser.add_option(
"-i",
"--ignore-environment",
51 help=
"start with an empty environment")
52 parser.add_option(
"-u",
"--unset",
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",
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",
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",
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)
88 return parser.parse_args()
92 Prepare an EnvConfig.Control instance to operate on the environment.
94 @param ignore_system: if set to True, the system environment is ignored.
96 from EnvConfig
import Control
97 control = Control.Environment()
100 control.presetFromSystem()
106 Return a dictionary of the environment variables after applying the actions.
108 @param ignore_system: if set to True, the system environment is ignored.
114 for action, args
in actions:
115 apply(getattr(control, action), args)
118 return control.vars()
122 Main function of the script.
131 for i, a
in enumerate(args):
136 if opts.shell
and cmd:
137 print >> sys.stderr,
"Invalid arguments: --%s cannot be used with a command." % opts.shell
140 env =
makeEnv(opts.actions, opts.ignore_environment)
142 if "LD_LIBRARY_PATH" in env:
144 if sys.platform.startswith(
"win"):
146 elif sys.platform.startswith(
"darwin"):
147 other =
"DYLD_LIBRARY_PATH"
152 env[other] = env[other] + os.pathsep + env[
"LD_LIBRARY_PATH"]
154 env[other] = env[
"LD_LIBRARY_PATH"]
155 del env[
"LD_LIBRARY_PATH"]
158 if opts.shell ==
'py':
159 from pprint
import pprint
162 template = {
'sh':
"export %s='%s'",
163 'csh':
"setenv %s '%s'"}.
get(opts.shell,
"%s=%s")
164 for nv
in sorted(env.items()):
168 from subprocess
import Popen
169 return Popen(cmd, env=env).wait()
171 if __name__ ==
"__main__":