Canonical embedded interactive Python interpreter example?

I would like to create a built-in Python interpreter in my C / C ++ application. Ideally, this interpreter will behave exactly like a real Python interpreter, but it will produce a result after processing each line of input. The standard Python module codelooks exactly the same from the outside as I do, except that it is written in Python. For instance:.

>>> 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 codeis a function that allows for potentially incomplete user input and either displays a syntax error (case 1), or expects more input (case 2), or performs 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

Python Demo/embed/demo.c - , , , . :

/* 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);
}

C , stacktraces .. Python. .

+3

Source: https://habr.com/ru/post/1783444/


All Articles