Last active
January 7, 2019 11:36
-
-
Save reidrac/cef6b83f53fbb27b05952f7d4c3df9df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
The env_file should have one KEY=VALUE per line and it can include spaces. | |
If the env_file is a JSON file (filename ends in .json), a list of dictionaries | |
is expected in the form: | |
[ { "name": "KEY", "value": "value" }, ... ] | |
To pass arguments to the commnd, use --; for example: | |
./env.py <file.env|env.json> ls -- -al | |
""" | |
import os | |
import argparse | |
import json | |
def main(): | |
parser = argparse.ArgumentParser(description="Load ENV variables and run a process.") | |
parser.add_argument("--inherit", "-i", dest="inherit", | |
action="store_true", help="Merge the env_file with current ENV") | |
parser.add_argument("env_file", help="File with ENV variables (one VAR=VALUE per line, or a JSON file)") | |
parser.add_argument("cmd", help="Command to execute") | |
parser.add_argument("args", nargs="*", help="Arguments") | |
args = parser.parse_args() | |
if args.inherit: | |
env = os.environ.copy() | |
else: | |
env = {} | |
if args.env_file.endswith(".json"): | |
with open(args.env_file, "r") as fd: | |
data = json.load(fd) | |
for line in data: | |
if not "name" in line or not "value" in line: | |
parser.error("invalid JSON format in %r" % args.env_file) | |
env[line["name"]] = line["value"] | |
else: | |
with open(args.env_file, "r") as fd: | |
lines = fd.readlines() | |
for line in lines: | |
line = line.strip() | |
if not line: | |
continue | |
k, v = line.split("=", 1) | |
env[k] = v | |
os.execvpe(args.cmd, [args.cmd,] + args.args, env) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment