Python Embedding, stdin/-out redirection

WDraxinger at darkstargames.de WDraxinger at darkstargames.de
Sun Mar 3 17:35:35 EST 2002


Hi there,
I'm just trying to embedd python in my 3D Engine
which works fine, except the problems with my console:
I'd like to do the
PyRun_InteractiveLoop(stdin, "<stdin>");
for my Engines console, because the python interactive
mode is just perfect. To make it as simple as possible
I redirected stdin/-out to 2 pipes which I read out
and print to my 3D window's console. Within my programm
all I/O stream releated stuff just works fine.
Mysteriously that doesn't work with python.
Below you see an example of what I tried:

#include <python.h>
#include <io.h>
#include <fcntl.h>

enum {PIPE_READ, PIPE_WRITE};
int stdin_pipe[2];
int stdout_pipe[2];
int stderr_pipe[2];

void python_thread()
{
 // Sync with console
 Py_Initialize();
 PyRun_InteractiveLoop(stdin, "<console>");
 Py_Finalize();
}

void console_thread()
{  
 // Sync with python
 // Show me the stuff written to stdout
 while(!eof(stdout_pipe[PIPE_READ]))
 {
  int r=read(stdout_pipe[PIPE_READ], buffer, 80);
  buffer[r]=0;
  cprintf(buffer);
 }

 // The same with stderr
 while(!eof(stderr_pipe[PIPE_READ]))
 {
  int r=read(stderr_pipe[PIPE_READ], buffer, 80);
  buffer[r]=0;
  cprintf(buffer);
 }
}

int main(int argc, char **argv)
{
 char buffer[80];

 _pipe(stdin_pipe, 512, 0);
 _pipe(stdout_pipe, 512, 0);
 _pipe(stderr_pipe, 512, 0);

 _dup2(stdin_pipe[PIPE_READ], 0);
 _dup2(stdout_pipe[PIPE_WRITE], 1);
 _dup2(stderr_pipe[PIPE_WRITE], 2);

 start_console_thread();
 start_python_thread();

 return 0;
}

The output of my programm code is written in the pipe,
but python output still goes to the system console.

I also tried
PyRun_SimpleString("os.dup2(<my_pipe_file_descriptor>, sys.stdout.fileno())\n");

but it doesn't work and python complies about an invalid file descriptor.
I thought it would share the files since it runs in the same process, doesn't they?
Has anybody an idea how to solve this problem.
-- 
+------------------------------------------------+
| +----------------+ WOLFGA
NG DRAXINGER          |
| | ,-.   DARKSTAR | lead programmer             |
| |(   ) +---------+ wdraxinger at darkstargames.de |
| | `-' / GAMES /                                |
| +----+''''''''     http://www.darkstargames.de |
+------------------------------------------------+





More information about the Python-list mailing list