How to depress the output of an external module ?

Sebastian 'lunar' Wiesner basti.wiesner at gmx.net
Tue Dec 26 09:32:21 EST 2006


fdu.xiaojf at gmail.com <fdu.xiaojf at gmail.com> wrote

> 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...

On Linux systems you may try os.open('/dev/stdout', os.O_WRONLY'). This
will connect to lowest available file descriptor to standard output. If
you're lucky and no files have been opened after closing standard
output, sys.stdout will point to standard output again.

Bye
Sebastian 'lunar' Wiesner

-- 
Freedom is always the freedom of dissenters.
                                      (Rosa Luxemburg)



More information about the Python-list mailing list