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