| 1 |
# |
| 2 |
# Licensed to the Apache Software Foundation (ASF) under one |
| 3 |
# or more contributor license agreements. See the NOTICE file |
| 4 |
# distributed with this work for additional information |
| 5 |
# regarding copyright ownership. The ASF licenses this file |
| 6 |
# to you under the Apache License, Version 2.0 (the |
| 7 |
# "License"); you may not use this file except in compliance |
| 8 |
# with the License. You may obtain a copy of the License at |
| 9 |
# |
| 10 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
# |
| 12 |
# Unless required by applicable law or agreed to in writing, |
| 13 |
# software distributed under the License is distributed on an |
| 14 |
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 |
# KIND, either express or implied. See the License for the |
| 16 |
# specific language governing permissions and limitations |
| 17 |
# under the License. |
| 18 |
# |
| 19 |
|
| 20 |
# |
| 21 |
# A platform-agnostic tool for running a program in a modified environment. |
| 22 |
# |
| 23 |
|
| 24 |
import sys |
| 25 |
import os |
| 26 |
import subprocess |
| 27 |
from optparse import OptionParser |
| 28 |
|
| 29 |
|
| 30 |
def main(argv=None): |
| 31 |
|
| 32 |
parser = OptionParser(usage="Usage: %prog [options] [--] VAR=VALUE... command [options] arg1 arg2...") |
| 33 |
parser.add_option("-i", "--ignore-environment", |
| 34 |
action="store_true", default=False, |
| 35 |
help="Start with an empty environment (do not inherit current environment)") |
| 36 |
|
| 37 |
(options, args) = parser.parse_args(args=argv) |
| 38 |
|
| 39 |
if options.ignore_environment: |
| 40 |
new_env = {} |
| 41 |
else: |
| 42 |
new_env = os.environ.copy() |
| 43 |
|
| 44 |
# pull out each name value pair |
| 45 |
while len(args): |
| 46 |
z = args[0].split("=", 1) |
| 47 |
if len(z) != 2: |
| 48 |
break # done with env args |
| 49 |
name, value = z[0], z[1] |
| 50 |
if len(name) == 0: |
| 51 |
raise Exception("Error: incorrect format for env var: '%s'" % str(args[0])) |
| 52 |
del args[0] |
| 53 |
if len(value) == 0: |
| 54 |
# value is not present, so delete it |
| 55 |
if name in new_env: |
| 56 |
del new_env[name] |
| 57 |
else: |
| 58 |
new_env[name] = value |
| 59 |
|
| 60 |
if len(args) == 0 or len(args[0]) == 0: |
| 61 |
raise Exception("Error: syntax error in command arguments") |
| 62 |
|
| 63 |
p = subprocess.Popen(args, env=new_env) |
| 64 |
return p.wait() |
| 65 |
|
| 66 |
|
| 67 |
if __name__ == "__main__": |
| 68 |
sys.exit(main()) |