Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout and stderr to same file using Python

I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use

$ python myfile.py &> out.txt

to do the same task that I want, but I need to do it from the Python script itself.

I looked into the questions Redirect subprocess stderr to stdout, How to redirect stderr in Python?, and Example 10.10 from here, and then I tried the following:

import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock

print "a"

which rightly prints the letter "a" in the file out.txt; however, when I try the following:

import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock

print "a   # missing end quote, will give error

I get the error message "SyntaxError ..." on the terminal, but not in the file out.txt. What do I need to do to send the SyntaxError to the file out.txt? I do not want to write an Exception, because in that case I have to write too many Exceptions in the script. I am using Python 2.7.

Update: As pointed out in the answers and comments below, that SyntaxError will always output to screen, I replaced the line

print "a   # missing end quote, will give error

by

print 1/0  # Zero division error

The ZeroDivisionError is output to file, as I wanted to have it in my question.

like image 736
gora Avatar asked Jan 06 '23 14:01

gora


1 Answers

This works

sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout
like image 59
yahya Avatar answered Jan 16 '23 22:01

yahya