How to depress the output of an external module ?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Dec 26 05:28:02 EST 2006


On Tue, 26 Dec 2006 15:49:10 +0800, fdu.xiaojf at gmail.com wrote:

> Hi,
> 
> I'm writing a program which imports an external module writing in C and
> calls a function provided by the module to do my job. But the method 
> produces
> a lot of output to the stdout, and this consumes most of the running time.
> 
> My question is, is there a way to depress the output produced by the
> function and hence make my program run faster? It's too complicated for me
> to modify the source code and recompile the external module.

Try something like this:

# WARNING: untested
def run_without_stdout(*args, **kwargs):
    function = args[0]
    args = args[1:]
    savestdout = sys.stdout
    sys.stdout = cStringIO.StringIO()
    result = None
    try:
        result = function(*args, **kwargs)
    finally:
        # don't forget to restore stdout, or you 
        # really will regret it...
        sys.stdout = savestdout
    return result



-- 
Steven.




More information about the Python-list mailing list