[Tutor] redirecting module output

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Aug 18 20:44:31 CEST 2004

> Ok, before I come to the problem, first on how the head of
> the main script (the GUI part) looks like:
> --------
> import sys
> import os
> import wx
> # import own modules from the 'src' directory
> import src.DNA
> import src.NCBIstrip
> class FindFrame(wx.Frame,src.DNA.DNA):

Hmm, FindFrame is not a very OO sounding name - its
a verb not a noun. Even if its the "Frame used for
Finding" rather than an action I'd query the fact
it inherits from DNA. Is it really a "kind of"
DNA object or does it use a DNA object?

Inheritance which is not truly "kind of" can cause
many complications later.

> Now to the problem: Functions of the 'DNA' class
> (within the DNA module) printed their output on
> the shell (stdout).

Ah but thats a bad design mistake. Functions should
return values not print out things. (Unless they are
display functions in which case you'd not be using
them in a GUI...) Thus you need to refactor your DNA
design to separate presentation from processing
- this is a fundamental design principle for any
kind of reuse.

> functions within DNA print something on the shell to
> indicate that the process is still running

Generally this will be done in a GUI by either setting
a timer to update a progress indicator or by posting
events if that is possible. EVent handlers should not
really have long running loops in them, and if they must
then those loops should run in a separate functionin
a separate thread.

> how is it possible to redirect the output from the
> imported DNA-class to 'TextField'?

The best way is to refactor your DNA code to avoid
having the functions that do the work printing things.
If you have a lot of in;line print statements you might
consider calling a function to do the display.
You can then write a text version and a GUI version of
the function and pass the function as a parameter to
the processing engine, like this:

def processIT(p1,p2,displayIT=displayText):
    # long process here
    for n in xrange(10000 * p1):
        displayIT("Here is a display string")
        x = (n * n/N ** 0.3)**2
    result = x ** p2
    displayIT("finished soon")
    return result

def displayText(s): print s

def displayGUI(s):
   # write your GUI code here


> Well, I hope I made myself clear. Describing this problem wasn't
easy ...

I hope I made my counter proposal clear?
There are ways to procede the way you suggest but they are not
a good way going forward. refactoring at this stage will be much
easier later on IMHO.

Alan G.

More information about the Tutor mailing list