-
Notifications
You must be signed in to change notification settings - Fork 1
/
execute_py.c
91 lines (73 loc) · 2.73 KB
/
execute_py.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
// -----------------------------------------------
// The function to run Python
// -----------------------------------------------
#define AS_STRING(X) AS_STRING2(X)
#define AS_STRING2(X) #X
// loads the function F from the shared lib
#define LOAD(F, R, ...) \
R (*F)(__VA_ARGS__); \
*(void**)(&F) = dlsym(libpython_handle, AS_STRING(F)); \
if ((error = dlerror()) != NULL) { \
fprintf(stderr, "%s\n", error); \
return 1; \
}
static void* libpython_handle = NULL;
//---------------------------------
int init_python_interpreter(const char* python_so) {
char* error;
libpython_handle = dlopen(python_so, RTLD_GLOBAL | RTLD_LAZY);
if (!libpython_handle) {
fprintf(stderr, "Can not find Python !\n%s\n", dlerror());
return 1;
}
dlerror(); // Clear any existing error
LOAD(Py_Initialize, void, ); // loads the functions that we will need
(*Py_Initialize)(); // initialize the interpreter
return 0;
}
//---------------------------------
int init_python_interpreter_from_env(const char* env_var) {
char *python_so = getenv(env_var);
if (!python_so) {
fprintf(stderr, "Can not find the environment variable %s\n", env_var);
return 1;
}
return init_python_interpreter(python_so);
}
//---------------------------------
int execute_python_file(const char* filename) {
char* error;
if (!libpython_handle) {
fprintf(stderr, "Python is not initialized. You forget to call init_python_interpreter !\n");
return 1;
}
// check Python is running
LOAD(Py_IsInitialized, int, );
if (!(*Py_IsInitialized)()) {
fprintf(stderr, "Python Interpreter failed to initialize");
return 1;
}
// Open the script file, report error, and run it in the interpreter
FILE* file = fopen(filename, "r");
if (!file) {
fprintf(stderr, "file %s not found \n", filename);
return 1;
}
// LOAD(PyRun_SimpleString, int, const char *);
LOAD(PyRun_SimpleFile, int, FILE*, const char*);
(*PyRun_SimpleFile)(file, filename);
return 0;
}
//---------------------------------
int close_python_interpreter() {
char* error;
// close the interpreter
LOAD(Py_Finalize, void, );
(*Py_Finalize)();
// close the shared lib
dlclose(libpython_handle);
return 0;
}