title: Capture c++ shared library log entries with ctypes
body: <p>I have a cplusplus shared library, with a c interface, that writes log entries in stdout. I'm using it in a python application using the <code>ctypes</code> library. The python application uses <code>logging</code> library to write log entries. </p>
  
  <p>What I need to do is to capture the stdout entries of the shared library to write the log entries with the <code>logging</code> module. In other words, I want to redirect the stdout entries of the c library to the <code>logging</code> module, so I can use <code>logging</code> to write to files and console using its handlers.</p>
  
  <p>I found that is possible to capture the stdout (<a href="https://stackoverflow.com/questions/9488560/capturing-print-output-from-shared-library-called-from-python-with-ctypes-module">see this SO question</a>), but I can access it only when the c module call ends, and hence it is useless for logging. I want a none-blocking way to access the stdout entries. </p>
  
  <p>A minimum example is as follows.</p>
  
  <p>module.cpp (compiled with <code>g++  -fPIC -shared  module.cpp -o module.so</code>)</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  extern "C" int callme()
  {
    cout&lt;&lt;"Hello world\n";
    sleep(2);
    cout&lt;&lt;"Some words\n";
    sleep(2);
    cout&lt;&lt;"Goodby world\n";
    return 0;
  }
  </code></pre>
  
  <p>The python app that calls it:</p>
  
  <pre><code>import ctypes as ct
  import logging
  
  format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG
  logging.basicConfig(format=format)
  
  logging.debug('This logging modules works like a charm!')
  
  mymodule = ct.CDLL('./module.so')
  mymodule.callme()
  
  logging.info('I want to capture the shared library log entries')
  logging.warning('Can I?')
  </code></pre>
  
  <p>This produces:</p>
  
  <pre><code>2016-02-04 16:16:35,976 - DEBUG - This logging modules works like a charm!
  Hello world
  Some words
  Goodby world
  2016-02-04 16:16:39,979 - INFO - I want to capture the shared library log entries
  2016-02-04 16:16:39,979 - WARNING - Can I?
  </code></pre>
  
  <p>I have access to the c++ library, so a solution that needs modifications in the library are also welcome.</p>