Getting stdout using ctypes.

Grant Edwards grante at visi.com
Thu Aug 14 12:58:42 EDT 2008


On 2008-08-14, Larry Bates <larry.bates at websafe.com`> wrote:
> Mathias Lorente wrote:
>> Hello all.
>> 
>> I have a simple application (C++) that relies on shared libraries. It 
>> works fine in console mode.
>> Lot of job is done into the shared library, so there is some calls to 
>> 'std::cout' to inform the user in it.
>> 
>> Now, I would like to wrap everything into a GUI, remove the application 
>> and call directly everything from Python using ctypes. (I still need the 
>> console application to launch it manually if needed).
>> I've made a simple library to test ctypes and everything works fine 
>> except that I don't know how to get stout in order to redirect it 
>> somewhere (dialog box or so).
>> 
>> I've looked for some help into the mailing list history and found 
>> nothing useful (until now).
>> Do someone has any suggestion?
>> 
>> Mathias
>> 
> If I'm understanding your question correctly, you can replace sys.stdout with 
> any class that provides a write method.
>
> class myStdout(object):
>      def __init__(self):
>          self.lines = list()
>
>      def write(self, data):
>          self.lines.append(data)
>
>
> Then in program do something like
>
> import sys
> sys.stdout = myStdout()
>
> Now everything that would have gone to stdout will be buffered into the list in 
> sys.stdout.lines.

That's not going to redirect output that C/C++ dlls are writing
to stdout (Which is what the OP wants to do AFAICT).

If he's running Unix, he needs to replace the stdout file
descriptor (fd 1), with something that's connected to the
"write" end of a pipe.  Then he needs to read the other
("read") end of the pipe in his application.

You do that using the dup2() system call:

http://www.unixwiz.net/techtips/remap-pipe-fds.html

-- 
Grant Edwards                   grante             Yow! I have a VISION!  It's
                                  at               a RANCID double-FISHWICH on
                               visi.com            an ENRICHED BUN!!



More information about the Python-list mailing list