Skip to content

Instantly share code, notes, and snippets.

@howardhamilton
Last active November 3, 2016 21:14

Revisions

  1. howardhamilton revised this gist Nov 3, 2016. 1 changed file with 18 additions and 8 deletions.
    26 changes: 18 additions & 8 deletions exec_cmd.py
    Original file line number Diff line number Diff line change
    @@ -1,13 +1,23 @@
    def execute_command(cmd, shell_flag=False):
    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 with 0.5 sec delay.
    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)
    """
    with io.open("tmp_output.log", 'wb') as writer, io.open("tmp_output.log", 'rb', 1) as reader:
    p = subprocess.Popen(cmd, stdout=writer, shell=shell_flag)
    while p.poll() is None:
    sys.stdout.write(reader.read().decode('utf-8'))
    time.sleep(0.5)
    sys.stdout.write(reader.read().decode('utf-8'))
    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)
  2. howardhamilton created this gist May 23, 2016.
    13 changes: 13 additions & 0 deletions exec_cmd.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    def execute_command(cmd, shell_flag=False):
    """
    Execute command using a subprocess, and write streaming output to the screen with 0.5 sec delay.
    :param cmd: Command-line statement
    :param shell_flag: Flag to run subprocess in a shell (default: False)
    """
    with io.open("tmp_output.log", 'wb') as writer, io.open("tmp_output.log", 'rb', 1) as reader:
    p = subprocess.Popen(cmd, stdout=writer, shell=shell_flag)
    while p.poll() is None:
    sys.stdout.write(reader.read().decode('utf-8'))
    time.sleep(0.5)
    sys.stdout.write(reader.read().decode('utf-8'))