Last active
October 25, 2022 06:36
-
-
Save rurumimic/3bb00a977f876f6ced97b700867636ea to your computer and use it in GitHub Desktop.
realtime subprocess output in python 2 & 3
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
import logging | |
import subprocess | |
logger = logging.getLogger() | |
logger.setLevel(logging.DEBUG) | |
logger.addHandler(logging.StreamHandler()) | |
def main(cmd): | |
try: | |
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) | |
while True: | |
out = proc.stdout.readline() | |
if out == '' and proc.poll() != None: | |
break | |
if out != '': | |
logger.debug(out.rstrip("\n")) | |
except subprocess.CalledProcessError as e: | |
logger.error(e.output) | |
raise e | |
except Exception as e: | |
raise e | |
if __name__ == "__main__": | |
main('echo "wait 1 sec" && sleep 1 && echo "ok, great."', ".") |
in python 3.x:
try:
stdout = subprocess.check_output(
cmd,
cwd=chdir,
timeout=TIMEOUT,
shell=True,
encoding="utf-8",
stderr=subprocess.STDOUT,
)
logger.debug(stdout)
except subprocess.TimeoutExpired as e:
logger.error(e.output)
raise e
except subprocess.CalledProcessError as e:
logger.error(e.output)
raise e
except Exception as e:
raise e
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in python 3.x: