Canonical embedded interactive Python interpreter example?
Question: I would like to create an embedded Python interpreter in my C/C++ application.
Ideally this interpreter would behave exactly like the real Python
interpreter, but yield after processing each line of input. The standard
Python module `code` looks from the outside exactly like what I want, except
that it is written in Python. E.g.:

    
    
    >>> import code
    >>> code.interact()
    Python 2.7.1 (r271:86832, Jan  3 2011, 15:34:27) 
    [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> 
    

The core of `code` is the function that accepts potentially incomplete user
input and either displays a syntax error (case 1), waits for more input (case
2), or executes the user input (case 3).

    
    
    try:
        code = self.compile(source, filename, symbol)
    except (OverflowError, SyntaxError, ValueError):
        # Case 1
        self.showsyntaxerror(filename)
        return False
    
    if code is None:
        # Case 2
        return True
    
    # Case 3
    self.runcode(code)
    return False
    

The example in the Python source tree `Demo/embed/demo.c` is the outer shell
but not what I want because that example only handles complete statements. I'm
including part of it here for reference:

    
    
    /* Example of embedding Python in another program */
    #include "Python.h"
    
    main(int argc, char **argv)
    {
        /* Initialize the Python interpreter.  Required. */
        Py_Initialize();
        [snip]
        /* Execute some Python statements (in module __main__) */
        PyRun_SimpleString("import sys\n");
        [snip]
        /* Exit, cleaning up the interpreter */
        Py_Exit(0);
    }
    

What I'm looking for is the C code to handle incomplete blocks, stacktraces,
etc. That is, all the behaviors of the real Python interpreter. Thanks in
advance.


Answer: Take a look at
[boost.python](http://www.boost.org/doc/libs/1_45_0/libs/python/doc/tutorial/doc/html/python/embedding.html#python.using_the_interpreter).
It's a fantastic integretaion of Python in C++ and vice versa.

But you are able to use the C API anyway. The
[PyRun_InteractiveLoopFlags()](http://docs.python.org/c-api/veryhigh.html#PyRun_InteractiveLoopFlags)
function offer a interactive console in your C++ application.

