Skip to content

Instantly share code, notes, and snippets.

@ecovictoriano
Created March 6, 2018 20:47
Show Gist options
  • Save ecovictoriano/dd30098fa72c0a7950dd677f1c5dbf69 to your computer and use it in GitHub Desktop.
Save ecovictoriano/dd30098fa72c0a7950dd677f1c5dbf69 to your computer and use it in GitHub Desktop.
Execute shell commands and get stdout message for long running commands with polling
from subprocess import Popen, PIPE
def shell_exec(cmd, cb=None, poll=True):
with Popen(cmd, stdout=PIPE, bufsize=1) as p:
if poll:
while p.poll() is None:
line = p.stdout.readline().decode('utf-8').strip()
if callable(cb): cb(line)
time.sleep(0.5)
for line in p.stdout.readlines():
line = line.decode('utf-8').rstrip()
if callable(cb): cb(line)
else:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment