Of course you need to have set up a logger using the logging module (see the other post).
Please be aware that copy and paste of the code below will most probably lead to indention error, as the code was more or less just a copy of respective passages in real code.
import subprocess
def executeExternalAndLog(cmd, logger, reErrorLine):
u"""Executes given 'exploded' command and logs its results to given logger.
Given compiled regular expression is used to log lines as errors.
"""
try:
result = \
subprocess.run(args=cmd,
check = True,
stdout = subprocess.PIPE, # to capture output
stderr = subprocess.PIPE, # to capture error
encoding = 'utf-8',
universal_newlines=True)
except subprocess.CalledProcessError as e:
logger.debug('Command: {}'.format(e.cmd)) # DEBUG because can contain password
logger.info('Return code: {}'.format(e.returncode))
logger.info("Stdout")
for line in e.stdout.splitlines():
if reErrorLine.match(line):
logger.error(line)
else:
logger.info(line)
logger.critical("Stderr")
for line in e.stderr.splitlines():
logger.critical(line)
raise
except:
logger.critical(sys.exc_info())
raise
else:
for line in result.stdout.splitlines():
logger.info(line)
A call could be done like this.
executeExternalAndLog(["sqlplus",
"-L",
'{}/{}@{}'.format(schema, password, instance),
"@install_master.sql"],
logger,
RE_ORACLE_ERROR_LINE)