// 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 #include #include #include #include #include bool plugin_initialized = false; bool plugin_construct() { if (plugin_initialized) return true; Py_Initialize(); if (!Py_IsInitialized()) { fprintf(stderr, "Failed to initialize Python interpreter\n"); return plugin_initialized; } plugin_initialized = true; return plugin_initialized; } void plugin_run(char *src) { plugin_construct(); const char *basics = "import sys\n" "import os\n" "import math\n" "import pathlib\n" "import subprocess\n" "import time\n" "from datetime import datetime\n" "%s"; size_t length = strlen(basics) + strlen(src); char *script = (char *)malloc(length + 1); sprintf(script, basics, src); script[length] = '\0'; PyRun_SimpleString(script); free(script); } void plugin_destruct() { if (plugin_initialized) Py_Finalize(); }