小能豆

Creating an interactive Python console in C or C++

py

I am create an application to send string to Python and read back the result as string again. Following the documentation;

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is', ctime(time()))\n");
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    PyMem_RawFree(program);
    return 0;
}

I am simply trying to achieve an interactive Python console in C or C. My problem is that PyRun_SimpleString is a one-shot function but I want my application to be interactive and continuous through the session. Can you give me a simple example of an interactive Python shell written in C or C?


阅读 59

收藏
2023-11-27

共1个答案

小能豆

Certainly! If you want an interactive Python shell in a C or C program, you can use the PyRun_InteractiveLoopFlags function provided by the Python C API. This function allows you to run an interactive interpreter loop within your C or C program.

Here’s an example:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int main(int argc, char *argv[]) {
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }

    Py_SetProgramName(program);
    Py_Initialize();

    // Run an interactive Python shell
    PyRun_InteractiveLoopFlags(stdin, "<stdin>");

    if (Py_FinalizeEx() < 0) {
        exit(120);
    }

    PyMem_RawFree(program);
    return 0;
}

In this example, the PyRun_InteractiveLoopFlags function runs an interactive interpreter loop, reading commands from the standard input (stdin). The loop continues until the user types an EOF character (usually Ctrl+D or Ctrl+Z, depending on your system).

Compile and run this program, and you should get an interactive Python shell in your console, allowing you to enter Python commands interactively.

2023-11-27