Skip to content

Instantly share code, notes, and snippets.

@HoldenLucas
Created June 13, 2023 21:56
Show Gist options
  • Save HoldenLucas/5720eaaa62d6aa4389f963b8cdf432a2 to your computer and use it in GitHub Desktop.
Save HoldenLucas/5720eaaa62d6aa4389f963b8cdf432a2 to your computer and use it in GitHub Desktop.
Python equivalent of `set -x`
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