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
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'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment