Skip to content

Instantly share code, notes, and snippets.

@ozkansen
Created May 27, 2020 12:38
Show Gist options
  • Save ozkansen/53e510bea1ffdbce8bc27011e3dfd51b to your computer and use it in GitHub Desktop.
Save ozkansen/53e510bea1ffdbce8bc27011e3dfd51b to your computer and use it in GitHub Desktop.
from subprocess import Popen, PIPE, TimeoutExpired
from typing import Tuple
def execute_command(
command: str, sudo: bool = False, shell: bool = False
) -> Tuple[str, str, int]:
"""
Subprocess Execute Command
Arguments:
command {str} -- example: command='ls -al'
Keyword Arguments:
sudo {bool} -- root permission (default: {False})
shell {bool} -- command run in shell (default: {False})
Returns:
Tuple[str, str, int] -- (stdout, stderr, returncode)
"""
command = command.split(" ")
if sudo is True:
command.insert(0, "sudo")
proc = Popen(command, stdout=PIPE, stderr=PIPE, shell=shell)
try:
outs, errs = proc.communicate(timeout=10)
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
outs = outs.decode()
errs = errs.decode()
code = proc.returncode
return (outs, errs, code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment