import os import shlex import subprocess import sys from typing import Callable def run(cmd: str, *, write_func: Callable = print, exit_on_error: bool = True) -> None: """ Runs provided command as child process, prints stdout and stderr and exists with error code, if child process exited with one. """ try: process = subprocess.run(cmd, shell=True, capture_output=True, check=True) except subprocess.CalledProcessError as exc: if exc.stdout: write_func(exc.stdout.decode()) if exc.stderr: write_func(exc.stderr.decode()) if exit_on_error: sys.exit(exc.returncode) else: raise if process.stdout: write_func(process.stdout.decode()) if process.stderr: write_func(process.stderr.decode()) def execute(cmd: str) -> None: """ Runs provided command and replaces process with current one. """ command = shlex.split(cmd) os.execvp(command[0], command)