Calling Py_Main() and parsing the output from C

Gisle Vanem gvanem at broadpark.no
Sat Aug 10 09:09:31 EDT 2013


Hello Python & C-experts.

I'm trying to embed python27.dll in a C-program written in
MingW-gcc 4.7.2. I've successfully done these initial steps:

  typedef int (*Py_Main_t) (int argc, char **argv);
  handle = LoadLibrary ("python27.dll");
  py_main = (Py_Main_t) GetProcAddress (handle, "Py_Main");
  argv[0] = who_am_I;    /* the .exe of the embedding program. python*.dll doesn't seems to care what this is */
  argv[1] = (char*) "-c";
  argv[2] = PYTHON_CMD;  /* see below */
  argv[3] = NULL;

  rc = (*py_main) (3, argv);

DEBUG: pyembed.c(76): Calling Py_Main():
  argv[0] = "G:\vc_2010\VC\Projects\EnvTool\src\envtool.exe"
  argv[1] = "-c"
  argv[2] = "import sys;[sys.stdout.write('%s\n' % p) for (i,p) in enumerate(sys.path)]"
  argv[3] = NULL.

Which produces the expected 'sys.path[]:
  g:\Programfiler\Python27\lib\site-packages\pyzmq-2.2.0.1-py2.7-win32.egg
  g:\Programfiler\Python27\lib\site-packages\nose-1.2.1-py2.7.egg
  ...

But I'd like to grab the stdout from Py_Main() into a pipe, mmap-file or similar
for the calling program to parse. Before I used the embedding solution, I simply 
spawned python.exe using my shell and popen(). Then parsed the output 
using fgets(). This work fine. But I'd like to try embedding now. Since avoiding 
the shell should be faster. No?

How can I accomplish the grabbing of Py_Main() output simplest? Is creating
a memory-mapped file in the calling program a good idea? Can Py_Main() print 
to that? If so, how? I'm on Win-XP SP3.

--gv



More information about the Python-list mailing list