Created
April 5, 2019 04:00
-
-
Save CMCDragonkai/2765ca91d7b33c5721eaa7edd01fad95 to your computer and use it in GitHub Desktop.
Run subprocess while connecting STDERR to Python logging system #python
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 io | |
import subprocess | |
import threading | |
import logging | |
def subprocess_with_logger(logger, check=False, *args, **kwargs): | |
def log_stream(pipe, logger): | |
# by default stderr will be a binary stream | |
# we wrap it into a text stream | |
pipe = io.TextIOWrapper(pipe, encoding='utf-8', newline='') | |
with pipe: | |
for line in pipe: | |
logger.info(line.rstrip('\n')) | |
with subprocess.Popen( | |
*args, bufsize=1, stderr=subprocess.PIPE, **kwargs) as proc: | |
logger_thread = threading.Thread( | |
target=log_stream, args=(proc.stderr, logger)) | |
logger_thread.start() | |
proc.wait() | |
logger_thread.join() | |
if check is True: | |
if proc.returncode != 0: | |
raise subprocess.CalledProcessError( | |
proc.returncode, proc.args, | |
proc.stdout.read() if proc.stdout is not None else None) | |
return proc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment