Created
June 12, 2022 15:50
-
-
Save rkhullar/37baef6694163fd5744947ab1ba152d8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| import os | |
| import re | |
| import subprocess | |
| from argparse import ArgumentParser, Namespace | |
| from dataclasses import dataclass, field | |
| def build_parser() -> ArgumentParser: | |
| parser: ArgumentParser = ArgumentParser(add_help=False, usage='%(prog)s {program} --env:{key} {val} {arg}') | |
| parser.add_argument('program', type=str) | |
| return parser | |
| @dataclass | |
| class Process: | |
| program: str | |
| args: list[str] = field(default_factory=list) | |
| environment: dict[str, str] = field(default_factory=dict) | |
| @classmethod | |
| def from_parser(cls, namespace: Namespace, args: list[str]) -> 'Process': | |
| process = Process(program=namespace.program) | |
| patterns = {'env': re.compile(r'^--env:(?P<key>\w+)$')} | |
| i: int = 0 | |
| while i < len(args): | |
| arg = args[i] | |
| if match_object := patterns['env'].match(arg): | |
| process.environment[match_object.group('key')] = args[i+1] | |
| i += 1 | |
| else: | |
| process.args.append(arg) | |
| i += 1 | |
| return process | |
| def run(self) -> int: | |
| parent_envs: dict[str, str] = dict(os.environ) | |
| pid: object = subprocess.run( | |
| args=[self.program]+self.args, | |
| env={**parent_envs, **self.environment}, | |
| check=False | |
| ) | |
| return pid.returncode | |
| if __name__ == '__main__': | |
| parser: ArgumentParser = build_parser() | |
| namespace, args = parser.parse_known_args() | |
| process: Process = Process.from_parser(namespace, args) | |
| print(process) | |
| return_code = process.run() | |
| exit(return_code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment