Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Created April 5, 2019 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CMCDragonkai/2765ca91d7b33c5721eaa7edd01fad95 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/2765ca91d7b33c5721eaa7edd01fad95 to your computer and use it in GitHub Desktop.
Run subprocess while connecting STDERR to Python logging system #python
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