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 ( ) {
if ( plugin_initialized )
2025-01-04 05:00:03 +00:00
return true ;
2025-01-04 07:35:39 +00:00
Py_Initialize ( ) ;
2025-01-04 05:00:03 +00:00
if ( ! Py_IsInitialized ( ) ) {
fprintf ( stderr , " Failed to initialize Python interpreter \n " ) ;
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-04 07:40:31 +00:00
const char * basics =
" import sys \n "
2025-01-04 05:00:03 +00:00
" 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 ) ;
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 ( ) {
if ( plugin_initialized )
2025-01-04 05:00:03 +00:00
Py_Finalize ( ) ;
}