How to depress the output of an external module ?

fdu.xiaojf at gmail.com fdu.xiaojf at gmail.com
Tue Dec 26 08:23:55 EST 2006


fdu.xiaojf at gmail.com wrote:
>
> I have tried your method, but I found it didn't work as expected.
>
> The output produced by the external function couldn't be depressed,
> but the "print " statement i wrote in python is depressed. It seems
> make cStringIO.StringIO() as a temporary replacement of sys.stdout
> has no effect on the external function.
>
> Here is an example to make myself clear(actually it's modified version
> of Steven's code):
>
> def run_without_stdout(*args, **kwargs):
>     function = args[0]
>     args = args[1:]
>     savestdout = sys.stdout
>     sys.stdout = cStringIO.StringIO()
>     print "something"
>     result = None
>     try:
>         result = function(*args, **kwargs)
>     finally:
>         # don't forget to restore stdout, or you 
>         # really will regret it...
>         sys.stdout = savestdout
>     print "some other thing"
>     return result
>
> When run_without_stdout() is called, the "print" statements wrote in python
> don't produce output, but function() produces output to the standard output
> just as before:(
>
> I have tried to replace sys.stdout globally with cStringIO.StringIO()
> in my program(I mean, make "sys.stdout = cStringIO.StringIO()" as a
> globall statement), but it worked just as previous version did.
>   
After some trials I found that put "os.close(1)" before calling the
function will depress the output. In fact, "os.close(1)" closed
standard output, but I don't know how to open it again after the function's
execution.

Still trying...

Regards,

xiaojf



More information about the Python-list mailing list