I use Python 2.7. This is what I'm doing currently to launch other programs from Python, redirecting STDOUT and STERR to LOGFILE:
try:
# Execute command and print content to LOGFILE
tempname = os.path.abspath('./text.txt')
TEMPFILE = open(tempname, 'wb')
print 'Executing: ', command
subprocess.check_call(command, shell = True, stdout = TEMPFILE, stderr = TEMPFILE)
TEMPFILE.close()
LOGFILE.write(open(tempname, 'rU').read())
LOGFILE.close()
os.remove(tempname)
except Exception as errmsg:
# If fails then print errors to LOGFILE
TEMPFILE.close()
LOGFILE.write(open(tempname, 'rU').read())
os.remove(tempname)
print messages.crit_error_bad_command % command, '\n', str(errmsg)
print >> LOGFILE, messages.crit_error_bad_command % command, '\n', str(errmsg)
LOGFILE.close()
First of all, I wasn't sure my above script was the best solution. I had to use a temp file because I want to capture the log even in the case the subprocess.check_call call fails. If you have ideas how to improve the above script I'd appreciate it.
Moreover, I would like to change this so that STDOUT and STDERR should go to the screen as normal AND also to the log file. How do I do this? Note that if I don't specify STDOUT, I'll see things like "There is an error, do you wish to continue [y/n]?" on the screen and then I can react to it. Right now since everything goes to the log, I do not see anything on the screen. The answer to my question here should help resolve this case.
Thanks.