Domanda

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
È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top