Skip to content

Instantly share code, notes, and snippets.

@Jim-Holmstroem
Last active October 17, 2017 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jim-Holmstroem/a1e71902687621d57aec1c4f8a21b10d to your computer and use it in GitHub Desktop.
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.
#!/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,
)
@Jim-Holmstroem
Copy link
Author

Jim-Holmstroem commented Oct 17, 2017

Usage example: ./with_context.py 'echo hello && echo world && echo $TEST'

@Jim-Holmstroem
Copy link
Author

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