embedding interactive python interpreter

Eric Frederich eric.frederich at gmail.com
Fri Mar 25 12:02:16 EDT 2011


I am able to embed the interactive Python interpreter in my C program
except that when the interpreter exits, my entire program exits.

    #include <stdio.h>
    #include <Python.h>

    int main(int argc, char *argv[]){
        printf("line %d\n", __LINE__);
        Py_Initialize();
        printf("line %d\n", __LINE__);
        Py_Main(argc, argv);
        printf("line %d\n", __LINE__);
        Py_Finalize();
        printf("line %d\n", __LINE__);
        return 0;
    }

When I run the resulting binary I get the following....

$ ./embedded_python
line 5
line 7
Python 2.7.1 (r271:86832, Mar 25 2011, 11:56:07)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hi'
hi
>>> exit()


I never see line 9 or 11 printed.
I need to embed python in an application that needs to do some cleanup
at the end so I need that code to execute.
What am I doing wrong?

Is there something else I should call besides "exit()" from within the
interpreter?
Is there something other than Py_Main that I should be calling?

Thanks,
~Eric



More information about the Python-list mailing list