Comment 4 for bug 1072694

Revision history for this message
Marco Morandini (morandini) wrote : Re: [Bug 1072694] Re: list_timings() cannot be redirected to a file or a variable in python

On 10/30/2012 08:00 AM, Johan Hake wrote:
> Marco, what would the syntax be for adding a file as the log output. Is
> it possible to add an already existing file pointer or just the file
> name as a string? This would be the ultimate solution as we then can
> merge the two log streams from dolfin and logging dependent python
> modules such as UFL.
>
> My boost python skills are really limited so following the inner
> workings of this small file is hard for me...
>

In my old code (where everything is wrapped with boost)

after

fileout = ostream(cout_buf())

fileout will point to std::cout,

and after

fileout = ostream('new_file_name.txt')

fileout will point to a newly opened ofstream.

Then, fileout can be passed to any wrapped c++ function that
has an std::ostream & argument.

I.e., if I have this c++ function

void DxOutput(std::ostream & out, const MyFloat t);

and I wrap it as

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(ofstream_open_overloads,
std::ofstream::open, 1, 2);
BOOST_PYTHON_MODULE_INIT(_python_util)
{
 ....

 the wrapping code I've attached

 ....

 python::def("DxOutput", DxOutput);
}

in python I can do

t=0.01
fileout = ostream('new_file_name.txt')
DxOutput(fileout, t)

if I want to write with DxOutput into new_file_name.txt,

or

fileout = ostream(cout_buf())
DxOutput(fileout, t)

If I want DxOuptut's output on the screen.

Note however that I can't write directly from python into fileout
(and I fear that this is what you are looking for :( .
At least, I've not even tried to do it (perhaps one should start
extractig the file descriptor, as explained here:

http://www.ginac.de/~kreckel/fileno/

)

Or
http://stackoverflow.com/questions/2378005/c-iostreams-and-python

Hope this helps.