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