57 lines
1.5 KiB
C
Raw Normal View History

2025-01-04 07:40:31 +00:00
// 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
2025-01-04 05:00:03 +00:00
#include <python3.14/Python.h>
#include <python3.14/structmember.h>
#include <stdbool.h>
2025-01-04 07:40:31 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2025-01-04 05:00:03 +00:00
bool plugin_initialized = false;
2025-01-04 07:40:31 +00:00
bool plugin_construct() {
2025-01-27 18:06:59 +00:00
if (plugin_initialized) return true;
2025-01-04 05:00:03 +00:00
2025-01-04 07:35:39 +00:00
Py_Initialize();
2025-01-04 05:00:03 +00:00
if (!Py_IsInitialized()) {
2025-01-27 18:06:59 +00:00
fprintf(stderr, "Failed to initialize the Python interpreter\n");
2025-01-04 05:00:03 +00:00
return plugin_initialized;
}
plugin_initialized = true;
return plugin_initialized;
}
2025-01-04 07:40:31 +00:00
void plugin_run(char *src) {
2025-01-04 05:00:03 +00:00
plugin_construct();
2025-01-27 18:06:59 +00:00
const char *basics =
2025-01-04 07:40:31 +00:00
"import sys\n"
2025-01-04 05:00:03 +00:00
"import os\n"
2025-01-26 01:54:45 +00:00
"from os import *\n"
2025-01-04 05:00:03 +00:00
"import math\n"
"import pathlib\n"
2025-01-26 01:54:45 +00:00
"from pathlib import Path\n"
"import re\n"
2025-01-04 05:00:03 +00:00
"import subprocess\n"
2025-01-26 01:54:45 +00:00
"from subprocess import *\n"
2025-01-04 05:00:03 +00:00
"import time\n"
"from datetime import datetime\n"
"%s";
size_t length = strlen(basics) + strlen(src);
2025-01-04 07:40:31 +00:00
char *script = (char *)malloc(length + 1);
2025-01-04 05:00:03 +00:00
sprintf(script, basics, src);
2025-01-04 07:40:31 +00:00
script[length] = '\0';
2025-01-04 05:00:03 +00:00
PyRun_SimpleString(script);
free(script);
}
2025-01-04 07:40:31 +00:00
void plugin_destruct() {
2025-01-27 18:06:59 +00:00
if (plugin_initialized) Py_Finalize();
}