To redirect all standard output of an external process to a file in Python:
#!/usr/bin/env python
from subprocess import check_call, STDOUT
with open('log', 'ab', 0) as file:
check_call(['program', 'arg 1', 'arg 2'], stdout=file, stderr=STDOUT)
The output is redirected as is. To make it conform to the logging format, you might need it to pass through your program explicitly:
#!/usr/bin/env python3
import logging
from subprocess import Popen, PIPE, STDOUT
logging.basicConfig(filename='log',level=logging.DEBUG)
with Popen(['program', 'arg 1', 'arg 2'], stdout=PIPE, stderr=STDOUT, bufsize=1,
universal_newlines=True) as process:
for line in process.stdout:
logging.debug('program output %s', line.rstrip('\n'))
The code decodes program's standard output using locale.getpreferredencoding(False)
and appends lines to the log file using logging
module (you could configure whatever logging format you like using standard logging
tools).