Created
June 13, 2023 21:56
-
-
Save HoldenLucas/5720eaaa62d6aa4389f963b8cdf432a2 to your computer and use it in GitHub Desktop.
Python equivalent of `set -x`
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
import logging | |
import subprocess | |
def sh(cmd: str, *, quiet: bool = False) -> str: | |
""" | |
The python equivalent of `set -x`. | |
Runs the provided `cmd`, returning stdout. | |
In case of a non-zero exit code, prints stdout and stderr. | |
""" | |
PROMPT_CHARACTER = "$" | |
if not quiet: | |
logging.info(f"{PROMPT_CHARACTER} {cmd}") | |
std_everything = bytearray() | |
process = subprocess.Popen( | |
cmd, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE | |
) | |
# print the output of the command in real time | |
for line in process.stdout: | |
std_everything.extend(line) | |
if not quiet: | |
print(line.decode(), end="") | |
return_code = process.wait() | |
dec_std_everything = std_everything.decode("ascii") | |
if return_code != 0: | |
logging.info(f"{PROMPT_CHARACTER} {cmd}") | |
logging.error(dec_std_everything) | |
raise subprocess.CalledProcessError(returncode=return_code, cmd=process.args) | |
return dec_std_everything |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment