I was checking the working of standard streams, and currently I am working with stderr
using python. To explain clearly, the following is my code:
print("Python")
testt()
when I run the code I get the following:
Python
Traceback (most recent call last):
File "C:/Python34/s3.py", line 5, in <module>
testt()
NameError: name 'testt' is not defined
Now I wanted to save the error message to a text file, so my code for that was as follows:
import sys
sys.stderr = open('err.txt', 'w') # I tried with 'err.log' also
print("Python")
testt()
sys.stderr.close()
sys.stderr = sys.__stderr__
Now when I run the program, the error is not being displayed in the python shell. It is not getting saved to the err.txt
file also.
When I checked the err.txt
file properties it shows that the file has been modified recently (i.e. the time when the program was run), but the file is blank. What might be the problem? I am using windows and python 3.4.
I installed python 3.5 and still get the same issue. I also tried using contextlib, but still unsuccessful. My modified code using contextlib
is as follows:
from contextlib import redirect_stdout, redirect_stderr
with open('C:/Users/Jeri_Dabba/Desktop/Shortcutz/test/outfile.txt', 'w') as file, redirect_stdout(file):
help(pow)
with open('C:/Users/Jeri_Dabba/Desktop/Shortcutz/test/errfile.log', 'a') as file1, redirect_stderr(file1):
testt()
redirect_stdout(file)
was working fine, it was saving the output to the file; whereas redirect_stderr(file1)
is not saving the stderr
to the file.
What might be the problem?