Created
March 6, 2018 20:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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