Skip to content Skip to sidebar Skip to footer

How To Redirect Stderr To A File In Python?

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

Solution 1:

Your code works fine (I mean: the redirection to stderr.). Note however than from python3.5 you can use contextlib.redirect_stderr's context manager to do this:

from contextlib import redirect_stderr

withopen('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__.

Post a Comment for "How To Redirect Stderr To A File In Python?"