3 * ***** BEGIN GPL LICENSE BLOCK *****
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20 * All rights reserved.
22 * This is a new part of Blender.
24 * Contributor(s): Willian P. Germano
26 * ***** END GPL LICENSE BLOCK *****
29 /** \file blender/python/generic/bpy_internal_import.c
37 #include "bpy_internal_import.h"
39 #include "MEM_guardedalloc.h"
41 #include "DNA_text_types.h"
43 #include "BLI_listbase.h"
44 #include "BLI_path_util.h"
45 #include "BLI_string.h"
46 #include "BLI_utildefines.h"
49 #include "BKE_text.h" /* txt_to_buf */
52 static Main *bpy_import_main= NULL;
54 /* 'builtins' is most likely PyEval_GetBuiltins() */
55 void bpy_import_init(PyObject *builtins)
60 PyDict_SetItemString(builtins, "__import__", item=PyCFunction_New(&bpy_import_meth, NULL)); Py_DECREF(item);
63 * XXX, use import hooks */
64 mod= PyImport_ImportModuleLevel((char *)"imp", NULL, NULL, NULL, 0);
66 PyDict_SetItemString(PyModule_GetDict(mod), "reload", item=PyCFunction_New(&bpy_reload_meth, NULL)); Py_DECREF(item);
70 BLI_assert(!"unable to load 'imp' module.");
75 static void free_compiled_text(Text *text)
78 Py_DECREF((PyObject *)text->compiled);
83 struct Main *bpy_import_main_get(void)
85 return bpy_import_main;
88 void bpy_import_main_set(struct Main *maggie)
90 bpy_import_main= maggie;
93 /* returns a dummy filename for a textblock so we can tell what file a text block comes from */
94 void bpy_text_filename_get(char *fn, size_t fn_len, Text *text)
96 BLI_snprintf(fn, fn_len, "%s%c%s", text->id.lib ? text->id.lib->filepath : bpy_import_main->name, SEP, text->id.name+2);
99 PyObject *bpy_text_import(Text *text)
105 if(!text->compiled) {
107 bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
109 buf= txt_to_buf(text);
110 text->compiled= Py_CompileString(buf, fn_dummy, Py_file_input);
113 if(PyErr_Occurred()) {
116 PySys_SetObject("last_traceback", NULL);
117 free_compiled_text(text);
122 len= strlen(text->id.name+2);
123 strncpy(modulename, text->id.name+2, len);
124 modulename[len - 3]= '\0'; /* remove .py */
125 return PyImport_ExecCodeModule(modulename, text->compiled);
128 PyObject *bpy_text_import_name(char *name, int *found)
131 char txtname[MAX_ID_NAME-2];
132 int namelen= strlen(name);
133 //XXX Main *maggie= bpy_import_main ? bpy_import_main:G.main;
134 Main *maggie= bpy_import_main;
139 printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
143 if (namelen >= (MAX_ID_NAME-2) - 3) return NULL; /* we know this cant be importable, the name is too long for blender! */
145 memcpy(txtname, name, namelen);
146 memcpy(&txtname[namelen], ".py", 4);
148 text= BLI_findstring(&maggie->text, txtname, offsetof(ID, name) + 2);
155 return bpy_text_import(text);
160 * find in-memory module and recompile
163 PyObject *bpy_text_reimport(PyObject *module, int *found)
169 //XXX Main *maggie= bpy_import_main ? bpy_import_main:G.main;
170 Main *maggie= bpy_import_main;
173 printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
179 /* get name, filename from the module itself */
180 if((name= PyModule_GetName(module)) == NULL)
183 if((filepath= (char *)PyModule_GetFilename(module)) == NULL)
186 /* look up the text object */
187 text= BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);
189 /* uh-oh.... didn't find it */
195 /* if previously compiled, free the object */
196 /* (can't see how could be NULL, but check just in case) */
198 Py_DECREF((PyObject *)text->compiled);
201 /* compile the buffer */
202 buf= txt_to_buf(text);
203 text->compiled= Py_CompileString(buf, text->id.name+2, Py_file_input);
206 /* if compile failed.... return this error */
207 if(PyErr_Occurred()) {
210 PySys_SetObject("last_traceback", NULL);
211 free_compiled_text(text);
215 /* make into a module */
216 return PyImport_ExecCodeModule((char *)name, text->compiled);
220 static PyObject *blender_import(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
222 PyObject *exception, *err, *tb;
225 PyObject *globals= NULL, *locals= NULL, *fromlist= NULL;
226 int level= -1; /* relative imports */
229 //PyObject_Print(args, stderr, 0);
230 static const char *kwlist[]= {"name", "globals", "locals", "fromlist", "level", NULL};
232 if(!PyArg_ParseTupleAndKeywords(args, kw, "s|OOOi:bpy_import_meth", (char **)kwlist,
233 &name, &globals, &locals, &fromlist, &level))
236 /* import existing builtin modules or modules that have been imported already */
237 newmodule= PyImport_ImportModuleLevel(name, globals, locals, fromlist, level);
242 PyErr_Fetch(&exception, &err, &tb); /* get the python error incase we cant import as blender text either */
244 /* importing from existing modules failed, see if we have this module as blender text */
245 newmodule= bpy_text_import_name(name, &found);
247 if(newmodule) {/* found module as blender text, ignore above exception */
249 Py_XDECREF(exception);
252 /* printf("imported from text buffer...\n"); */
254 else if (found==1) { /* blender text module failed to execute but was found, use its error message */
255 Py_XDECREF(exception);
261 /* no blender text was found that could import the module
262 * rause the original error from PyImport_ImportModuleEx */
263 PyErr_Restore(exception, err, tb);
270 * our reload() module, to handle reloading in-memory scripts
273 static PyObject *blender_reload(PyObject *UNUSED(self), PyObject *module)
275 PyObject *exception, *err, *tb;
276 PyObject *newmodule= NULL;
279 /* try reimporting from file */
280 newmodule= PyImport_ReloadModule(module);
284 /* no file, try importing from memory */
285 PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use */
287 newmodule= bpy_text_reimport(module, &found);
288 if(newmodule) {/* found module as blender text, ignore above exception */
290 Py_XDECREF(exception);
293 /* printf("imported from text buffer...\n"); */
295 else if (found==1) { /* blender text module failed to execute but was found, use its error message */
296 Py_XDECREF(exception);
302 /* no blender text was found that could import the module
303 * reuse the original error from PyImport_ImportModuleEx */
304 PyErr_Restore(exception, err, tb);
310 PyMethodDef bpy_import_meth= {"bpy_import_meth", (PyCFunction)blender_import, METH_VARARGS | METH_KEYWORDS, "blenders import"};
311 PyMethodDef bpy_reload_meth= {"bpy_reload_meth", (PyCFunction)blender_reload, METH_O, "blenders reload"};
314 /* Clear user modules.
315 * This is to clear any modules that could be defined from running scripts in blender.
317 * Its also needed for the BGE Python api so imported scripts are not used between levels
319 * This clears every modules that has a __file__ attribute (is not a builtin)
321 * Note that clearing external python modules is important for the BGE otherwise
322 * it wont reload scripts between loading different blend files or while making the game.
323 * - use 'clear_all' arg in this case.
325 * Since pythons built-ins include a full path even for win32.
326 * even if we remove a python module a re-import will bring it back again.
329 #if 0 // not used anymore but may still come in handy later
331 #if defined(WIN32) || defined(WIN64)
338 void bpy_text_clear_modules(int clear_all)
340 PyObject *modules= PyImport_GetModuleDict();
343 char *file_extension;
345 /* looping over the dict */
346 PyObject *key, *value;
353 return; /* should never happen but just incase */
357 /* go over sys.modules and remove anything with a
358 * sys.modukes[x].__file__ thats ends with a .py and has no path
360 while (PyDict_Next(modules, &pos, &key, &value)) {
361 fname= PyModule_GetFilename(value);
363 if (clear_all || ((strstr(fname, SEPSTR))==0)) { /* no path ? */
364 file_extension= strstr(fname, ".py");
365 if(file_extension && (*(file_extension + 3) == '\0' || *(file_extension + 4) == '\0')) { /* .py or pyc extension? */
366 /* now we can be fairly sure its a python import from the blendfile */
367 PyList_Append(list, key); /* free'd with the list */
376 /* remove all our modules */
377 for(pos=0; pos < PyList_GET_SIZE(list); pos++) {
378 /* PyObject_Print(key, stderr, 0); */
379 key= PyList_GET_ITEM(list, pos);
380 PyDict_DelItem(modules, key);
383 Py_DECREF(list); /* removes all references from append */