63 lines
1.4 KiB
C
Raw Normal View History

2025-01-04 08:40:31 +01:00
// Written by retoor@molodetz.nl
2025-03-28 06:56:36 +01:00
// 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.
2025-01-04 08:40:31 +01:00
2025-03-28 06:56:36 +01:00
// 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.
2025-01-04 08:40:31 +01:00
// MIT License
2025-03-16 22:46:09 +01:00
#include <Python.h>
2025-01-04 06:00:03 +01:00
#include <stdbool.h>
2025-01-04 08:40:31 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2025-03-28 06:56:36 +01:00
#include <structmember.h>
2025-01-04 06:00:03 +01:00
bool plugin_initialized = false;
2025-01-04 08:40:31 +01:00
bool plugin_construct() {
2025-03-28 06:56:36 +01:00
if (plugin_initialized)
2025-03-03 17:06:05 +01:00
return true;
2025-03-28 06:56:36 +01:00
Py_Initialize();
if (!Py_IsInitialized()) {
fprintf(stderr, "Failed to initialize the Python interpreter\n");
return false;
}
plugin_initialized = true;
return true;
2025-01-04 06:00:03 +01:00
}
2025-01-04 08:40:31 +01:00
void plugin_run(char *src) {
2025-03-28 06:56:36 +01:00
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);
2025-01-04 06:00:03 +01:00
}
2025-01-04 08:40:31 +01:00
void plugin_destruct() {
2025-03-28 06:56:36 +01:00
if (plugin_initialized)
Py_Finalize();
2025-03-16 22:46:09 +01:00
}