Python subprocess.check_call - how to direct stdout and stderr to _both_ file and log file?

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.

+4
source share
1 answer

I will see things like "An error has occurred, do you want to continue [y / n]?" on the screen, and then I can respond to it.

To redirect the 'stdout subprocess and interact with the process either manually or using predefined answers, you can use pexpect :

 from contextlib import closing import pexpect with open('text.txt', 'rb') as logfile: with closing(pexpect.spawn(command, logfile=logfile)) as child: # call here child.expect(), child.sendline(), child.interact(), etc 

Implementing the same functionality using subprocess.Popen not trivial .

+1
source

All Articles