I am using Python 2.7. This is what I am currently doing to run other Python programs, 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 was not sure if my above script was a better solution. I had to use a temporary file because I want to capture the log even if subprocess.check_call fails. If you have any ideas for improving the above script, I would appreciate it.
In addition, I would like to change this so that STDOUT and STDERR should go to the screen as usual, as well as to the log file. How can I do it? Please note: if I do not specify STDOUT, I will see things like "There is an error, do you want to continue [y / n]?" on the screen, and then I can respond to it. Right now, when everything goes to the magazine, I canβt see anything on the screen. The answer to my question here should help resolve this case.
Thanks.
source share