Forgetful Interpreter

Bill Orcutt b_orcutt at pobox.com
Fri Oct 17 17:21:26 EDT 2003


Having seen the number of lost souls asking questions about embedding
Python in the archives of this group, I hesitate to add myself to
their number, but I've hit a problem I can't quite get my head around.

I have a simple C program that embeds a python interpreter to execute
python commands and return stdout, and to a point everything works as
intended. The problem that each command seems to be executed in its
own context and knows nothing of what's come before. So if enter
"print 2+2", I get back "4", but if I enter "a=2+2" then enter "print
a", I get back the error, "a is undefined." My guess is that this has
something to calling PyRun_SimpleString inside of a child process, but
I can't get much further than this.

Any assistance is appreciated.

thanks

-Bill

//call this once at the beginning to initialize 
void * nyptho_doinit(t_gogo* x, short flag)
{
    Py_Initialize();
    char capture_stdout[] ="import sys,
StringIO\n\sys.stderr=sys._capture=StringIO.StringIO()\n";
    int rc = PyRun_SimpleString(capture_stdout);
    return x;
}

//this executes the command
FILE * nyptho_exec(t_gogo* x, char * cmd, short bflag, short fflag)
{
    int		pfd[2],i,z=0;
    pid_t		pid;
    FILE		*fp;
    extern int 		errno;

    if (pipe(pfd) < 0)
                return(NULL);	// errno set by pipe()
    
        if ( (pid = fork()) < 0)
                return(NULL);	// errno set by fork()
       
         else if (pid == 0) // child
         {		
            close(pfd[0]);
    
            // close all descriptors in childpid[]
            if (x->childpid[0] > 0)
                    close(0);
                    
                PyRun_SimpleString(cmd);
                
                //PyRun_SimpleString("import sys");
                PyObject* sysmod = PyImport_ImportModule("sys");
                PyObject* capobj =
PyObject_GetAttrString(sysmod,"_capture");
                PyObject* strres =
PyObject_CallMethod(capobj,"getvalue",0);
                char * dodo = PyString_AsString(strres);
                strcpy(globalBuf,dodo);

                write(pfd[1], globalBuf, (long)strlen(globalBuf));
                globalBuf[0]='\0';
                                           
            _exit(127);	//child exits            
        }        
        // parent 
        close(pfd[1]);
        
        if ( (fp = fdopen(pfd[0], "r")) == NULL)
                return(NULL);
    
        x->childpid[fileno(fp)] = pid;	// remember child pid for this
fd
        return(fp);

}




More information about the Python-list mailing list