Last active
April 21, 2024 11:07
-
-
Save VehpuS/f22d81800dd20ebd41b6281e10e5a760 to your computer and use it in GitHub Desktop.
Run bash command from python
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
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