Last active
November 3, 2016 21:14
-
-
Save howardhamilton/0372f017a169b495a89c9b611be75ae0 to your computer and use it in GitHub Desktop.
Execute command using a subprocess and write streaming output to the screen
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 logging | |
import subprocess | |
from io import BytesIO | |
def execute_command(cmd, ns=__name__, shell_flag=False): | |
""" | |
Execute command using a subprocess, and write streaming output to the screen. | |
:param cmd: Command-line statement | |
:param ns: Namespace to be used in logging | |
:param shell_flag: Flag to run subprocess in a shell (default: False) | |
""" | |
def report(level, _lines): | |
for line in BytesIO(_lines).read().decode('utf-8').split(u'\n'): | |
if line != u'': | |
getattr(logging.getLogger(ns), level)(line.strip()) | |
logging.getLogger(ns).debug(cmd) | |
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell_flag) | |
stdout, stderr = proc.communicate() | |
report('info', stdout) | |
report('error', stderr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment