Back to project.

Raw source file available here .

// Written by retoor@molodetz.nl

// This source code initializes a Python interpreter within a plugin, executes a
// provided Python script with some basic imports, and finalizes the Python
// environment when done.

// This code does not use any non-standard imports or includes aside from
// Python.h and structmember.h which are part of Python's C API.

// MIT License

#include <Python.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <structmember.h>

bool plugin_initialized = false;

bool plugin_construct() {
if (plugin_initialized)
return true;

Py_Initialize();
if (!Py_IsInitialized()) {
fprintf(stderr, "Failed to initialize the Python interpreter\n");
return false;
}
plugin_initialized = true;
return true;
}

void plugin_run(char *src) {
plugin_construct();
/*const char *basics =
"import sys\n"
"import os\n"
"from os import *\n"
"import math\n"
"import pathlib\n"
"from pathlib import Path\n"
"import re\n"
"import subprocess\n"
"from subprocess import *\n"
"import time\n"
"from datetime import datetime\n"
"%s";
*/
const char *basics = "\n\n";
size_t length = strlen(basics) + strlen(src);
char *script = malloc(length + 1);
sprintf(script, basics, src);
script[length] = '\0';
PyRun_SimpleString(script);
free(script);
}

void plugin_destruct() {
if (plugin_initialized)
Py_Finalize();
}