14#include <frameobject.h>
16#ifdef WITH_PYTHON_MODULE
17# include "pylifecycle.h"
93static int bpy_timer_count = 0;
95static double bpy_timer;
97static double bpy_timer_run;
99static double bpy_timer_run_tot;
122 *gilstate = PyGILState_Ensure();
129 if (bpy_timer_count == 0) {
132 bpy_timer_run = bpy_timer_run_tot = 0.0;
146 PyGILState_Release(*gilstate);
150 fprintf(stderr,
"ERROR: Python context internal state bug. this should not happen!\n");
176 const char *context_members[],
177 uint context_members_len)
179 PyGILState_STATE gilstate;
183 gilstate = PyGILState_Ensure();
187 if (*dict_p == dict_orig) {
188 *dict_p = PyDict_Copy(
static_cast<PyObject *
>(dict_orig));
191 PyObject *dict =
static_cast<PyObject *
>(*dict_p);
196 for (
uint i = 0; i < context_members_len; i++) {
197 PyObject *key = PyUnicode_FromString(context_members[i]);
198 PyObject *item = _PyDict_Pop(dict, key, Py_None);
204 PyGILState_Release(gilstate);
210 if (text->compiled) {
211 PyGILState_STATE gilstate;
215 gilstate = PyGILState_Ensure();
218 Py_DECREF((PyObject *)text->compiled);
219 text->compiled =
nullptr;
222 PyGILState_Release(gilstate);
232 PyObject *
mod = PyImport_ImportModuleLevel(
"bpy",
nullptr,
nullptr,
nullptr, 0);
256#ifdef WITH_AUDASPACE_PY
263static PyObject *CCL_initPython()
295#ifdef WITH_AUDASPACE_PY
299 {
"_cycles", CCL_initPython},
309#ifndef WITH_PYTHON_MODULE
321 if (
UNLIKELY(PyStatus_Exception(status))) {
322 fputs(
"Internal error initializing Python!\n", stderr);
324 Py_ExitStatusException(status);
331#ifndef WITH_PYTHON_MODULE
332 BLI_assert_msg(Py_IsInitialized() == 0,
"Python has already been initialized");
336 PyPreConfig preconfig;
343 "Initializing %s support for the systems Python environment such as 'PYTHONPATH' and "
344 "the user-site directory.",
348 PyPreConfig_InitPythonConfig(&preconfig);
354 PyPreConfig_InitIsolatedConfig(&preconfig);
370 preconfig.utf8_mode =
true;
375 status = Py_PreInitialize(&preconfig);
386 bool has_python_executable =
false;
389 PyConfig_InitPythonConfig(&config);
392 PyConfig_InitIsolatedConfig(&config);
397 config.pathconfig_warnings = 0;
409 config.parse_argv = 0;
410 status = PyConfig_SetBytesArgv(&config, argc, (
char *
const *)argv);
420 status = PyConfig_SetBytesString(&config, &config.program_name, program_path);
429 program_path,
sizeof(program_path), PY_MAJOR_VERSION, PY_MINOR_VERSION))
431 status = PyConfig_SetBytesString(&config, &config.executable, program_path);
433 has_python_executable =
true;
438 "Unable to find the Python binary, "
439 "the multiprocessing module may not be functional!\n");
447 if (py_path_bundle.has_value()) {
453 if (strchr(py_path_bundle->c_str(),
':')) {
455 "Warning! Blender application is located in a path containing ':' or '/' chars\n"
456 "This may make Python import function fail\n");
460 status = PyConfig_SetBytesString(&config, &config.home, py_path_bundle->c_str());
463# ifdef PYTHON_SSL_CERT_FILE
465 const char *ssl_cert_file_env =
"SSL_CERT_FILE";
466 if (
BLI_getenv(ssl_cert_file_env) ==
nullptr) {
467 const char *ssl_cert_file_suffix = PYTHON_SSL_CERT_FILE;
470 ssl_cert_file,
sizeof(ssl_cert_file), py_path_bundle->c_str(), ssl_cert_file_suffix);
477# if defined(__APPLE__) || defined(_WIN32)
479 "Bundled Python not found and is expected on this platform "
480 "(the 'install' target may have not been built)\n");
486 status = Py_InitializeFromConfig(&config);
487 PyConfig_Clear(&config);
491 if (!has_python_executable) {
492 PySys_SetObject(
"executable", Py_None);
499 Py_DECREF(PyImport_ImportModule(
"threading"));
517#ifdef WITH_PYTHON_MODULE
520 struct _inittab *inittab_item;
521 PyObject *sys_modules = PyImport_GetModuleDict();
524 PyObject *
mod = inittab_item->initfunc();
526 PyDict_SetItemString(sys_modules, inittab_item->name,
mod);
545#ifndef WITH_PYTHON_MODULE
550 PyEval_ReleaseThread(PyGILState_GetThisThreadState());
554#ifdef WITH_PYTHON_MODULE
556 const char *imports[] = {
"atexit",
"addon_utils",
nullptr};
563#ifndef WITH_PYTHON_MODULE
564 BLI_assert_msg(Py_IsInitialized() != 0,
"Python must be initialized");
567 PyGILState_STATE gilstate;
570 gilstate = PyGILState_Ensure();
593#ifndef WITH_PYTHON_MODULE
597 if (do_python_exit) {
602 PyGILState_Release(gilstate);
603 (void)do_python_exit;
611 printf(
"tot exec: %d, ", bpy_timer_count);
612 printf(
"tot run: %.4fsec, ", bpy_timer_run_tot);
613 if (bpy_timer_count > 0) {
614 printf(
"average run: %.6fsec, ", (bpy_timer_run_tot / bpy_timer_count));
617 if (bpy_timer > 0.0) {
618 printf(
"tot usage %.4f%%", (bpy_timer_run_tot / bpy_timer) * 100.0);
627 BLI_assert_msg(Py_IsInitialized() != 0,
"Python must be initialized");
631 G.autoexec_fail[0] =
'\0';
651 fputs(
"\n# Python backtrace\n", fp);
654 if (!_PyThreadState_UncheckedGet()) {
657 PyFrameObject *frame = PyEval_GetFrame();
658 if (frame ==
nullptr) {
662 PyCodeObject *code = PyFrame_GetCode(frame);
663 const int line = PyFrame_GetLineNumber(frame);
664 const char *filepath = PyUnicode_AsUTF8(code->co_filename);
665 const char *funcname = PyUnicode_AsUTF8(code->co_name);
666 fprintf(fp,
" File \"%s\", line %d in %s\n", filepath, line, funcname);
667 }
while ((frame = PyFrame_GetBack(frame)));
672 const PyGILState_STATE gilstate = PyGILState_Ensure();
673 Py_DECREF((PyObject *)pyob_ptr);
674 PyGILState_Release(gilstate);
679 const PyGILState_STATE gilstate = PyGILState_Ensure();
680 const bool do_invalidate = (Py_REFCNT((PyObject *)pyob_ptr) > 1);
681 Py_DECREF((PyObject *)pyob_ptr);
685 PyGILState_Release(gilstate);
690 PyGILState_STATE gilstate;
695 if (bmain ==
nullptr) {
707 text =
static_cast<Text *
>(text->id.next))
713 SNPRINTF(
G.autoexec_fail,
RPT_(
"Text '%s'"), text->id.name + 2);
715 printf(
"scripts disabled for \"%s\", skipping '%s'\n",
735 PyGILState_STATE gilstate;
744 gilstate = PyGILState_Ensure();
748 item = PyDict_GetItemString(pyctx, member);
750 if (item ==
nullptr) {
753 else if (item == Py_None) {
764 else if (PySequence_Check(item)) {
765 PyObject *seq_fast = PySequence_Fast(item,
"bpy_context_get sequence conversion");
766 if (seq_fast ==
nullptr) {
771 const int len = PySequence_Fast_GET_SIZE(seq_fast);
772 PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
775 for (i = 0; i <
len; i++) {
776 PyObject *list_item = seq_fast_items[i];
785 "'%s' list item not a valid type in sequence type '%s'",
787 Py_TYPE(item)->tp_name);
809 PyGILState_Release(gilstate);
815#ifdef WITH_PYTHON_MODULE
818static void bpy_module_free(
void *
mod);
821extern int main_python_enter(
int argc,
const char **argv);
822extern void main_python_exit();
824static struct PyModuleDef bpy_proxy_def = {
825 PyModuleDef_HEAD_INIT,
843static void bpy_module_delay_init(PyObject *bpy_proxy)
849 PyObject *filepath_obj = PyModule_GetFilenameObject(bpy_proxy);
852 const char *filepath_rel = PyUnicode_AsUTF8(filepath_obj);
853 char filepath_abs[1024];
855 STRNCPY(filepath_abs, filepath_rel);
857 Py_DECREF(filepath_obj);
859 argv[0] = filepath_abs;
862 main_python_enter(argc, argv);
865 PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(
bpy_package_py));
872static bool bpy_module_ensure_compatible_version()
878 const uint version_runtime = Py_Version;
880 uint version_compile_major = PY_VERSION_HEX >> 24;
881 uint version_compile_minor = ((PY_VERSION_HEX & 0x00ff0000) >> 16);
882 uint version_runtime_major = version_runtime >> 24;
883 uint version_runtime_minor = ((version_runtime & 0x00ff0000) >> 16);
884 if ((version_compile_major != version_runtime_major) ||
885 (version_compile_minor != version_runtime_minor))
887 PyErr_Format(PyExc_ImportError,
888 "The version of \"bpy\" was compiled with: "
889 "(%u.%u) is incompatible with: (%u.%u) used by the interpreter!",
890 version_compile_major,
891 version_compile_minor,
892 version_runtime_major,
893 version_runtime_minor);
899static void dealloc_obj_dealloc(PyObject *
self);
901static PyTypeObject dealloc_obj_Type;
904static void dealloc_obj_dealloc(PyObject *
self)
906 bpy_module_delay_init(((dealloc_obj *)
self)->
mod);
910 dealloc_obj_Type.tp_free(
self);
913PyMODINIT_FUNC PyInit_bpy();
915PyMODINIT_FUNC PyInit_bpy()
917 if (!bpy_module_ensure_compatible_version()) {
921 PyObject *bpy_proxy = PyModule_Create(&bpy_proxy_def);
941 dealloc_obj_Type.tp_name =
"dealloc_obj";
942 dealloc_obj_Type.tp_basicsize =
sizeof(dealloc_obj);
943 dealloc_obj_Type.tp_dealloc = dealloc_obj_dealloc;
944 dealloc_obj_Type.tp_flags = Py_TPFLAGS_DEFAULT;
946 if (PyType_Ready(&dealloc_obj_Type) < 0) {
950 dob = (dealloc_obj *)dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
951 dob->mod = bpy_proxy;
952 PyModule_AddObject(bpy_proxy,
"__file__", (PyObject *)dob);
957static void bpy_module_free(
void * )
967 const char *kwlist[] = {
968 "False",
"None",
"True",
"and",
"as",
"assert",
"async",
"await",
"break",
969 "class",
"continue",
"def",
"del",
"elif",
"else",
"except",
"finally",
"for",
970 "from",
"global",
"if",
"import",
"in",
"is",
"lambda",
"nonlocal",
"not",
971 "or",
"pass",
"raise",
"return",
"try",
"while",
"with",
"yield",
nullptr,
974 for (
int i = 0; kwlist[i]; i++) {
PyObject * AUD_initPython(void)
const char * BKE_appdir_program_path() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
bool BKE_appdir_program_python_search(char *program_filepath, size_t program_filepath_maxncpy, int version_major, int version_minor) ATTR_NONNULL(1)
std::optional< std::string > BKE_appdir_folder_id(int folder_id, const char *subfolder) ATTR_WARN_UNUSED_RESULT
void CTX_wm_operator_poll_msg_clear(bContext *C)
Main * CTX_data_main(const bContext *C)
@ CTX_DATA_TYPE_COLLECTION
void CTX_data_list_add_ptr(bContextDataResult *result, const PointerRNA *ptr)
void CTX_data_pointer_set_ptr(bContextDataResult *result, const PointerRNA *ptr)
void * CTX_py_dict_get(const bContext *C)
void CTX_data_type_set(bContextDataResult *result, short type)
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL
const char * BKE_main_blendfile_path(const Main *bmain) ATTR_NONNULL()
bool text_check_identifier_nodigit(char ch)
bool text_check_identifier(char ch)
#define BLI_assert_msg(a, msg)
File and directory operations.
void BLI_setenv(const char *env, const char *val) ATTR_NONNULL(1)
#define BLI_path_join(...)
const char * BLI_getenv(const char *env) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
bool BLI_path_abs_from_cwd(char *path, size_t path_maxncpy) ATTR_NONNULL(1)
#define STRNCPY(dst, src)
#define SNPRINTF(dst, format,...)
int BLI_thread_is_main(void)
Platform independent time functions.
double BLI_time_now_seconds(void)
void BPY_app_handlers_reset(bool do_all)
struct CLG_LogRef * BPY_LOG_RNA
struct CLG_LogRef * BPY_LOG_CONTEXT
bool bool BPY_run_text(bContext *C, Text *text, ReportList *reports, bool do_jump) ATTR_NONNULL(1
bool BPY_run_string_eval(bContext *C, const char *imports[], const char *expr)
void * CCL_python_module_init(void)
#define CLG_LOGREF_DECLARE_GLOBAL(var, id)
#define CLOG_INFO(clg_ref, level,...)
Read Guarded memory(de)allocation.
PyMODINIT_FUNC BPyInit_bl_math()
PyObject * BPyInit_bmesh()
PyObject * BPyInit_bmesh_geometry()
PyObject * BPyInit_bmesh_types()
PyObject * BPyInit_bmesh_utils()
PyObject * bpy_package_py
void BPy_init_modules(bContext *C)
void BPY_atexit_unregister()
void BPY_atexit_register()
struct CLG_LogRef * BPY_LOG_INTERFACE
void BPY_app_translations_end()
int text_check_identifier_nodigit_unicode(const uint ch)
bool BPY_string_is_keyword(const char *str)
void BPY_python_use_system_env()
void BPY_context_dict_clear_members_array(void **dict_p, void *dict_orig, const char *context_members[], uint context_members_len)
int text_check_identifier_unicode(const uint ch)
int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
void BPY_modules_update()
bContext * BPY_context_get()
void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
void BPY_context_set(bContext *C)
static void pystatus_exit_on_error(const PyStatus &status)
void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
void BPY_python_backtrace(FILE *fp)
static void bpy_context_end(bContext *C)
void BPY_python_reset(bContext *C)
static bool py_use_system_env
void BPY_context_update(bContext *C)
void BPY_python_end(const bool do_python_exit)
static _inittab bpy_internal_modules[]
bool BPY_python_use_system_env_get()
void BPY_text_free_code(Text *text)
void bpy_context_clear(bContext *, const PyGILState_STATE *gilstate)
void BPY_modules_load_user(bContext *C)
void BPY_python_start(bContext *C, int argc, const char **argv)
void BPY_DECREF(void *pyob_ptr)
void bpy_intern_string_exit()
void bpy_intern_string_init()
PyObject * BPyInit__bpy_path()
void BPY_rna_props_clear_all()
void pyrna_invalidate(BPy_DummyPointerRNA *self)
PyObject * BPY_rna_module()
PyObject * BPY_rna_types()
void BPY_update_rna_module()
BPy_StructRNA * bpy_context_module
#define BPy_StructRNA_Check(v)
PyObject * BPyInit_idprop()
PyObject * BPyInit_imbuf()
PyObject * Manta_initPython(void)
PyMODINIT_FUNC PyInit_mathutils()
PyMODINIT_FUNC PyInit_mathutils_geometry()
PyMODINIT_FUNC PyInit_mathutils_kdtree()
PyMODINIT_FUNC PyInit_mathutils_noise()
bool PyC_IsInterpreterActive()
PyObject * BPyInit_hydra()
PyObject_HEAD PointerRNA ptr
ccl_device_inline int mod(int x, int m)