Last active
October 17, 2017 13:13
-
-
Save Jim-Holmstroem/a1e71902687621d57aec1c4f8a21b10d to your computer and use it in GitHub Desktop.
Wrap a shell command in python, for examplem standup, setup and teardown of a fixture for a test.
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 python3 | |
from itertools import ( | |
starmap, | |
) | |
import sys | |
import subprocess | |
import shlex | |
def main( | |
env_command, | |
aws, | |
): | |
print("---") | |
result = subprocess.run( | |
env_command, | |
shell=True, | |
) | |
print("---") | |
sys.exit(result.returncode) | |
if __name__ == "__main__": | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument("command_word", nargs=argparse.ZERO_OR_MORE) | |
args = parser.parse_args() | |
env = { | |
"test": "value", | |
} | |
env_command = "/usr/bin/env {environment} sh -c {command}".format( | |
environment=" ".join(starmap( | |
lambda name, value: "{}={}".format(name.upper(), value), | |
env.items() | |
)), | |
command=shlex.quote(" ".join(args.command_word)), | |
) | |
print(env_command) | |
main( | |
env_command=env_command, | |
) |
Just found that you could skip the environment
part in the above script and instead just inject it to subprocess.open(.., env=<>, ..)
. A much cleaner solution
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example:
./with_context.py 'echo hello && echo world && echo $TEST'