Skip to content

Instantly share code, notes, and snippets.

@marc0x71
Created May 8, 2024 17:57
Show Gist options
  • Save marc0x71/8229a31e42aeb1f154424f033a740b9c to your computer and use it in GitHub Desktop.
Save marc0x71/8229a31e42aeb1f154424f033a740b9c to your computer and use it in GitHub Desktop.
Execute the external command in Python
import shlex
from subprocess import Popen, PIPE
def get_exitcode_stdout_stderr(cmd: str):
"""
Execute the external command and get its exitcode, stdout and stderr.
"""
args = shlex.split(cmd)
proc = Popen(args, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
exitcode = proc.returncode
return exitcode, out, err
def get_exitcode_stdout_stderr_pipes(cmds: list[str]):
"""
Execute the external commands (in pipes) and get last exitcode, stdout and stderr.
"""
prev_stdin = None
process: Popen[str] = None
for cmd in cmds:
args = shlex.split(cmd)
if prev_stdin is not None:
process = Popen(args, stdout=PIPE, stderr=PIPE, stdin=prev_stdin)
else:
process = Popen(args, stdout=PIPE, stderr=PIPE)
prev_stdin = process.stdout
out, err = process.communicate()
exitcode = process.returncode
return exitcode, out, err
exitcode, out, err = get_exitcode_stdout_stderr("ls -lrt")
print(f"{exitcode=}")
print(f"{out=}")
print(f"{err=}")
exitcode, out, err = get_exitcode_stdout_stderr_pipes(
["ps -ef", "grep root", "head -5"]
)
print(f"{exitcode=}")
print(f"{out=}")
print(f"{err=}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment