plugins: python renderer: Make python scripts work from all directories

This commit is contained in:
Mario Hüttel 2019-11-17 17:12:15 +01:00
parent b610b1593a
commit b27676e0a4

View File

@ -31,6 +31,7 @@
*/ */
#include <stdio.h> #include <stdio.h>
#include <libgen.h>
#include <glib.h> #include <glib.h>
#include <unistd.h> #include <unistd.h>
#include <Python.h> #include <Python.h>
@ -87,9 +88,13 @@ int FUNC_DECL(EXTERNAL_LIBRARY_INIT_FUNCTION)(const char *params, const char *ve
int ret = 0; int ret = 0;
PyObject *p_name; PyObject *p_name;
PyObject *p_sys_path; PyObject *p_sys_path;
PyObject *p_cwd_string; PyObject *p_mod_dir_string;
PyObject *gds_render_module; PyObject *gds_render_module;
char cwd[256]; char file_path[PATH_MAX];
char *file_path_for_dir;
char *file_path_for_base;
char *dir_name;
char *base_name;
if (!params || !version) if (!params || !version)
return -1000; return -1000;
@ -98,24 +103,43 @@ int FUNC_DECL(EXTERNAL_LIBRARY_INIT_FUNCTION)(const char *params, const char *ve
ret = PyImport_AppendInittab("gds_render", &init_gds_render_module); ret = PyImport_AppendInittab("gds_render", &init_gds_render_module);
if (ret) { if (ret) {
ret = -1;
fprintf(stderr, "Registration of gds_render python module failed\n"); fprintf(stderr, "Registration of gds_render python module failed\n");
goto return_value; goto return_value;
} }
Py_Initialize(); Py_Initialize();
if (!getcwd(cwd, sizeof(cwd))) { if (!realpath(params, file_path)) {
fprintf(stderr, "Error getting current working directory. Maybe the path is too long?\n");
ret = -2; ret = -2;
fprintf(stderr, "Invalid file name.\n");
goto return_value; goto return_value;
} }
p_sys_path = PySys_GetObject("path"); file_path_for_dir = strdup(file_path);
p_cwd_string = PyUnicode_FromString(cwd); if (!file_path_for_dir) {
PyList_Append(p_sys_path, p_cwd_string); ret = -3;
Py_DECREF(p_cwd_string); goto return_value;
}
p_name = PyUnicode_DecodeFSDefault(params); file_path_for_base = strdup(file_path);
if (!file_path_for_base) {
ret = -3;
free (file_path_for_dir);
goto return_value;
}
dir_name = dirname(file_path_for_dir);
base_name = basename(file_path_for_base);
printf("Dir name : %s\n BAse name: %s\n", dir_name, base_name);
p_sys_path = PySys_GetObject("path");
p_mod_dir_string = PyUnicode_FromString(dir_name);
PyList_Append(p_sys_path, p_mod_dir_string);
Py_DECREF(p_mod_dir_string);
p_name = PyUnicode_DecodeFSDefault(strtok(base_name, "."));
p_module = PyImport_Import(p_name); p_module = PyImport_Import(p_name);
Py_DECREF(p_name); Py_DECREF(p_name);
@ -126,6 +150,9 @@ int FUNC_DECL(EXTERNAL_LIBRARY_INIT_FUNCTION)(const char *params, const char *ve
goto return_value; goto return_value;
} }
free(file_path_for_dir);
free(file_path_for_base);
return_value: return_value:
return ret; return ret;
} }