Created
May 8, 2024 17:57
-
-
Save marc0x71/8229a31e42aeb1f154424f033a740b9c to your computer and use it in GitHub Desktop.
Execute the external command in Python
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 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