Created
April 20, 2021 19:04
-
-
Save plredmond/8e558d309fa6b2c697b13a6ba5cca38d to your computer and use it in GitHub Desktop.
linux has a useful tool `env` to run a subprocess in a modified environment; i wrote a quick minimal version of it in python which might help windows users
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 | |
import os | |
import sys | |
import argparse | |
import subprocess | |
desc = ''' | |
run a program in a modified environment | |
example: run a tiny python script that reads the value of the variable "FOO" | |
{prog} --vars FOO=42 -- python -c 'import os; print(os.environ[\"FOO\"])' | |
'''.format(prog=sys.argv[0]).strip() | |
def main(opts): | |
if opts.verbose: | |
print(opts) | |
env = dict() if opts.ignore_environment else dict(os.environ) | |
env.update(opts.vars) | |
result = subprocess.run([opts.command] + opts.args, env=env) | |
return result.returncode | |
def pair(s): | |
name, _, value = s.partition('=') | |
return name, value | |
def parse(argv): | |
ap = argparse.ArgumentParser( | |
formatter_class=argparse.RawTextHelpFormatter, | |
description=desc | |
) | |
ap.add_argument('--vars', metavar='NAME=VALUE', type=pair, default=list(), nargs='*', help="Set each NAME to VALUE in the environment") | |
ap.add_argument('--verbose', action='store_true') | |
ap.add_argument('--ignore-environment', action='store_true') | |
ap.add_argument('command', metavar='COMMAND', help="Program to run") | |
ap.add_argument('args', metavar='ARG', nargs='*', help="Arguments to the program") | |
return ap.parse_args(argv) | |
if __name__ == '__main__': | |
sys.exit(main(parse(sys.argv[1:]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment