0

In this example, I want to write to console (std.out) in the try block; but when an exception is thrown by the except block, I want to write the exception content to std.err which is re-directed to a log file.

I could just have a file opened in except block and write on to it. but that needs to be done for every try-catch block, so if there is an alternative for re-directing these exceptions to std.err and log the std.error.

>>> try:
...   print "hello world"
...   1/0
... except ZeroDivisionError as e:
...   print "exception"
... 
hello world
exception
roippi
  • 25,533
  • 4
  • 48
  • 73
eagertoLearn
  • 9,772
  • 23
  • 80
  • 122
  • I didn't vote, but I can't make heads nor tails of the question (when you write something to stdout, that causes some other output to be redirected to stderr???) – NPE Jan 24 '14 at 02:51
  • @NPE: I am re-formatting the question. – eagertoLearn Jan 24 '14 at 02:59
  • @LegoStormtroopr: I know of this `print>> sys.stderr, 'spam'`. But I want to know if I could re-direct all sys.stderr to a file instead of it defaulting to console. – eagertoLearn Jan 24 '14 at 03:03

2 Answers2

5

It is absolutely possible:

import sys
sys.stderr = open("/tmp/errors.txt", "w")

And all following prints to stderr will go to that file.

You should probably be doing this at the shell level rather than at the Python level, though -- it's far more flexible.

Max Noel
  • 8,810
  • 1
  • 27
  • 35
  • This has the (probably) unwanted side effect of silencing *all* Exception tracebacks by piping them into the file the asker is trying to print to. –  Jan 24 '14 at 03:12
  • 1
    Well OP *did* ask how to redirect all of stderr to a file. But I agree -- like I said, that's a bad idea, and something better done at the shell level. – Max Noel Jan 24 '14 at 03:16
  • 1
    @MaxNoel: Thanks for a solution. atleast I know this is possible, but I will not do it – eagertoLearn Jan 24 '14 at 03:18
2

If you want to print to stderr, use sys.stderr and let the OS and user handle where the text printed to std.err goes. This allows a user to run python your_script.py 2> my_err_output on a Posix terminal and still catch the std.err content.

If you want to output logging information to a specific file, use the logging module instead.

Don't modify the behaviour of a very standard concept - that would be in err. Proper logging allows you to catch the information you need but allows expection tracebacks (which are piped to stderr) to get to the user without having to find your special file.