Skip to content

Instantly share code, notes, and snippets.

@VehpuS
Last active April 21, 2024 11:07
Show Gist options
  • Save VehpuS/f22d81800dd20ebd41b6281e10e5a760 to your computer and use it in GitHub Desktop.
Save VehpuS/f22d81800dd20ebd41b6281e10e5a760 to your computer and use it in GitHub Desktop.
Run bash command from python
import subprocess
import sys
def run_os_cmd(
cmd: str, # Command to run
interactive_write: bool=True, # Should the command print as it's running
):
print(f"Running '{cmd}'")
cmd_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True )
if interactive_write:
for c in iter(lambda: cmd_proc.stderr.read(1), b""):
sys.stdout.buffer.write(c)
for c in iter(lambda: cmd_proc.stdout.read(1), b""):
sys.stdout.buffer.write(c)
output, errors = cmd_proc.communicate()
if not interactive_write:
print(str(output.decode()))
if cmd_proc.returncode:
raise Exception(f"RUN failed\n\n{errors.decode()}\n\n")
elif errors and not interactive_write:
raise Exception(str(errors.decode()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment