Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect stderr in Python?

I would like to log all the output of a Python script. I tried:

import sys  log = []  class writer(object):     def write(self, data):         log.append(data)  sys.stdout = writer() sys.stderr = writer() 

Now, if I "print 'something' " it gets logged. But if I make for instance some syntax error, say "print 'something# ", it wont get logged - it will go into the console instead.

How do I capture also the errors from Python interpreter?

I saw a possible solution here:

http://www.velocityreviews.com/forums/showpost.php?p=1868822&postcount=3

but the second example logs into /dev/null - this is not what I want. I would like to log it into a list like my example above or StringIO or such...

Also, preferably I don't want to create a subprocess (and read its stdout and stderr in separate thread).

like image 573
EcirH Avatar asked Dec 24 '09 00:12

EcirH


People also ask

How do I redirect stderr?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.

What is stderr Python?

Python stderr is known as a standard error stream. It is similar to stdout because it also directly prints to the console but the main difference is that it only prints error messages. Example: import sys sys.stderr.write("This is error msg")


1 Answers

I have a piece of software I wrote for work that captures stderr to a file like so:

import sys sys.stderr = open('C:\\err.txt', 'w') 

so it's definitely possible.

I believe your problem is that you are creating two instances of writer.

Maybe something more like:

import sys  class writer(object):     log = []      def write(self, data):         self.log.append(data)  logger = writer() sys.stdout = logger sys.stderr = logger 
like image 142
KingRadical Avatar answered Sep 19 '22 15:09

KingRadical