[Tutor] Redirecting output

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 17 May 2001 23:49:18 +0200


On  0, John Murray <pursang@interact.net.au> wrote:
> I'm building a tkinter front end for an existing command line program. When 
> this is started from the cl it prints out a couple of lines of text to 
> indicate that it has started OK etc. I'd like to redirect this to a label 
> widget or similar in the front end. However, when I start it from the cl with 
> stdout or stderr (or both) redirected to a text file, the output doesn't 
> appear on screen (this is normal) but the file created remains empty. Where 
> is the output going? Redirecting stdout from shell commands works normally. 
> A bit off-topic I know but hoping someone can help.

I have no idea, really. If this is Windows, there are problems with
redirecting, maybe this is part of that, I don't know.

However, you can also redirect output from Python, by setting sys.stdout to
some other file like object (like an object you made that has a write()
method that puts the text in the label).

import sys

class MyOutput:
   def write(self, s):
       # Add s to label here
       pass

try:
   sys.stdout = MyOutput()
   # Call the rest of the program here
finally:
   # It's good practice to restore stdout even if there was an exception
   sys.stdout = sys._stdout

-- 
Remco Gerlich