[SciPy-user] optimize.fmin_tnc - how to catch its output?

Robert Kern robert.kern@gmail....
Mon Jul 21 18:22:29 CDT 2008

On Mon, Jul 21, 2008 at 17:56, Stéfan van der Walt <stefan@sun.ac.za> wrote:
> Hi Marek
> 2008/7/21 Marek Wojciechowski <mwojc@p.lodz.pl>:
>> Hallo!
>> I tried to catch fmin_tnc output to a file in the following way:
>>    file = open('messages', 'w')
>>    stdout = sys.stdout
>>    stderr = sys.stderr
>>    sys.stdout = file
>>    sys.stderr = file
>>    res = optimize.fmin_tnc(..., messages=1)
>>    file.close()
>>    sys.stdout = stdout
>>    sys.stderr = stderr
>> But this does not work. I realized that fmin_tnc calls C routine which
>> probably uses its own stdout, stderr. Is there a way to catch its output?
> I'm afraid you are right.  The quickest way I can think of is to grab
> it using standard unix pipes:
> python optimise_script.py 2>&1 | cat > out.txt

There is a way to redirect it to a (temporary) file from within
Python. You can then read this file. I have an old and
not-recently-tested implementation over here:


> Otherwise, the C-code will have to be modified.  Does anybody know
> what the best way is to write to sys.stdout and sys.stderr (not printf
> that goes to /dev/stdout) via the Python C API?

PySys_WriteStdout() and PySys_WriteStderr() as long as the output is
coming from the C extension modules themselves. Modifying the
library's C or (hah!) FORTRAN code is less palatable.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
 -- Umberto Eco

More information about the SciPy-user mailing list