Skip to content

Instantly share code, notes, and snippets.

@howardhamilton
Last active November 3, 2016 21:14
Show Gist options
  • Save howardhamilton/0372f017a169b495a89c9b611be75ae0 to your computer and use it in GitHub Desktop.
Save howardhamilton/0372f017a169b495a89c9b611be75ae0 to your computer and use it in GitHub Desktop.
Execute command using a subprocess and write streaming output to the screen
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