Python - How to redirect stderr to a file?
Question: The following code I got from <http://forums.devshed.com/python-
programming-11/redirect-stdout-stderr-file-500952.html> which tells how to
redirect a stderr to a file. I tried it but the error message is not getting
saved to the file. While I am not using

    
    
    sys.stderr = file_err
    

the error is displayed in the idle terminal, when I am assigning file_err to
sys.stderr the error is not displayed in the idle terminal, and it is not
being copied to the file_name.log

    
    
    import sys
    
    original_stderr = sys.stderr
    file_err = open('file_name.log', 'w') # I tried with .txt also
    sys.stderr = file_err
    print(list[file]) # Used to create a NameError
    sys.stderr = original_stderr
    file_err.close()
    

Am I supposed to write it to the file or is there an error in the program?


Answer: Your code works fine (I mean: the redirection to stderr.). Note however than
from python3.5 you can use
[`contextlib.redirect_stderr`](https://docs.python.org/3.5/library/contextlib.html#contextlib.redirect_stderr)'s
context manager to do this:

    
    
    from contextlib import redirect_stderr
    
    with open('filename.log', 'w') as stderr, redirect_stderr(stderr):
        # errors from here are logged to the file.
    

Note:

  * You don't have to explicitly call `close`.
  * You don't have to explicitly save the old stderr and restore it at the end.

By the way: instead of saving the old `stderr` value you could simply use
`sys.__stderr__`.

