Stdout in Real time

Is there any way I can modify the below code so I get the stdout output in real time. Currently this prints to a tkinter label when the function is completed and not during the execution.

Below is my code, I have added the flush myself and tried varies permutations but to no avail.

> class StdoutRedirector22(object):
>     def __init__(self):
>         self.result = ''
>
def write(self, text):
    self.result += text

def flush(self):
    pass

def blahblah(1,2):

from blah import blahblah2
old_stdout = sys.stdout   
sys.stdout = StdoutRedirector22()
blahblah2(1,2)
STATUS3['text'] = sys.stdout.result.strip()
sys.stdout = old_stdout`Preformatted text`

Hello,

when entering your script, can you please follow these instructions to make the script more readable:

From a quick glance, there are some syntax errors:

… should be:

def __init__(def):

This:

When defining a new function (ahem, method), you don’t include arguments (actual values) but rather parameters (variables) as placeholders.

Perhaps:

def blahblah(x, y):

And finally …

This method does nothing. Just because you call it flush, does not mean that it is actually flushing the contents.

You also need to import:

import sys

to make use of its methods.

import sys
class StdoutRedirector22(object):
def init(self):
self.result = ‘’

def write(self, text):
    self.result += text

def flush(self):
    pass
def blahblah(1,2):

from blah import blahblah2
old_stdout = sys.stdout   
sys.stdout = StdoutRedirector22()
blahblah2(1,2)
STATUS3['text'] = sys.stdout.result.strip()
sys.stdout = old_stdout

If I understand you correctly, you want to immediately react to blahblah2 writing something to sys.stdout, as opposed to waiting for it to finish and then reading a value from a buffer? If so, you can probably just add the relevant logic to the write method of your file I/O mock-up. Something like

class StdoutRedirector22:
    # ...
    def write(self, text):
        STATUS3['text'] = text

You might also find contextlib.redirect_stdout helpful.

Even better would be if blahblah2 returned a value to begin with instead of writing to stdout. Do you know why it’s doing that / is it something under your control?

Hi , i’ve reformatted. The functions aren’t the issue it’s getting the flush to work and output a result in real time.

This might be a small oversight, but you need to include indentation as Python is an indentation centric language.

Example:

class SomeClass:

    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2

If there are functions below a class definition, and there is no indentation, this will imply that they are not methods of the class (independent functions). However, if they are indented, then this specifies that they belong to the class.

… you still need to correct the syntactic errors in your “updated” script.

This done it , many thanks. I’ve been messing around with flush and getting nowhere