Display console output to status bar in Tkinter?

Alex Martelli alex at magenta.com
Thu Aug 10 09:11:48 EDT 2000


"rhyde99" <rhyde99 at email.msn.com> wrote in message
news:#Toh7OpAAHA.401 at cpmsnbbsa08...
> I need to know how it is possible to display only the last line of
> stdout/stderr output to my Tkinter status bar.  In the Python FAQ I saw a
> way to catch stdout/stderr output, but this method concatenates all of the
> output.  I just need the last line.
>
> I hope this is clear, and that someone can help!

When you set sys.stdout to your object, its write method gets called.
You will have to analyze it yourself to see about "lines", since there
is no apriori way to tell whether the argument to write comes as a
single print "a\nb\n\c\n" (three lines at once), a series of print 'x',
including the comma (one line made up of many call) or anything
in-between.

E.g., say you have a 'refresh' function that takes a single argument,
a line (entire or fragment), and shows it somewhere appropriately.
Then, the following may indicate the kind of thing you desire; the
test-part uses win32api's handy message-box function, but you can
omit that, of course, and e.g. write to a textfile to see what's going
on in more detail (including debugging output regarding what's
coming in to the write method, and what it is doing in consequence).


import string
import sys

class LastLiner:
    def __init__(self,refresh):
        self.refr=(refresh,)
        self.text=''
        self.last_sent=''
    def write(self,text):
        self.text=self.text+text
        linend=string.rfind(self.text,'\n',0,-1)
        tosend=self.text[linend+1:]
        if tosend[-1]=='\n':
            tosend=tosend[:-1]
        if tosend!=self.last_sent:
            self.refr[0]('Ref:'+tosend+':feR')
            self.text=self.last_sent=tosend

import win32api
def ref(tex):
    win32api.MessageBox(0, tex, 'MB_OK')

sys.stdout=LastLiner(ref)

print 'ciao\nmamma'
print '\n'
print 'foo',
print 'bar',
print 'baz',
print 'pepe!'
print 'a\nb\nc\nd\n'


As you can see, the code to determine what "the last line"
is, is not quite trivial, in order to be able to handle the
various cases "sensibly".  And your exact desires may be
different (e.g. in the test case, is 'the last line' a d, or is
it empty...?  I've gone to some trouble to let the d come,
but that may not be what you want!).  You may be able
to do some simplification, or tweaking to get exactly
your desired effect.


Alex






More information about the Python-list mailing list