Created
May 27, 2020 12:38
-
-
Save ozkansen/53e510bea1ffdbce8bc27011e3dfd51b to your computer and use it in GitHub Desktop.
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
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