14#include <frameobject.h>
17#ifdef WITH_PYTHON_MODULE
18# include "pylifecycle.h"
29#ifdef WITH_PYTHON_MODULE
100static int bpy_timer_count = 0;
102static double bpy_timer;
104static double bpy_timer_run;
106static double bpy_timer_run_tot;
131 PyGILState_STATE *gilstate,
132 const bool allow_null_context)
134 bool context_set =
false;
138 *gilstate = PyGILState_Ensure();
142 if (!allow_null_context) {
143 BLI_assert_msg(
C !=
nullptr,
"bpy: Trying to set invalid nullptr context");
154 if (bpy_timer_count == 0) {
157 bpy_timer_run = bpy_timer_run_tot = 0.0;
183 PyGILState_Release(*gilstate);
187 fprintf(stderr,
"ERROR: Python context internal state bug. this should not happen!\n");
210 if (
C ==
nullptr) [[unlikely]] {
218 const char *context_members[],
219 uint context_members_len)
221 PyGILState_STATE gilstate;
224 gilstate = PyGILState_Ensure();
228 if (*dict_p == dict_orig) {
229 *dict_p = PyDict_Copy(
static_cast<PyObject *
>(dict_orig));
232 PyObject *dict =
static_cast<PyObject *
>(*dict_p);
237 for (
uint i = 0; i < context_members_len; i++) {
238 PyObject *key = PyUnicode_FromString(context_members[i]);
241 switch (PyDict_Pop(dict, key, &item)) {
258 PyGILState_Release(gilstate);
264 if (text->compiled) {
265 PyGILState_STATE gilstate;
269 gilstate = PyGILState_Ensure();
272 Py_DECREF((PyObject *)text->compiled);
273 text->compiled =
nullptr;
276 PyGILState_Release(gilstate);
286 PyObject *
mod = PyImport_ImportModuleLevel(
"bpy",
nullptr,
nullptr,
nullptr, 0);
312static PyObject *CCL_initPython()
343#ifdef WITH_AUDASPACE_PY
347 {
"_cycles", CCL_initPython},
357#ifndef WITH_PYTHON_MODULE
369 if (PyStatus_Exception(status)) [[unlikely]] {
370 fputs(
"Internal error initializing Python!\n", stderr);
372 Py_ExitStatusException(status);
379#ifndef WITH_PYTHON_MODULE
380 BLI_assert_msg(Py_IsInitialized() == 0,
"Python has already been initialized");
386 std::optional(
false) :
391 PyPreConfig preconfig;
396 "Initializing %s support for the systems Python environment such as 'PYTHONPATH', "
397 "%s support for the user-site directory.",
402 PyPreConfig_InitPythonConfig(&preconfig);
408 PyPreConfig_InitIsolatedConfig(&preconfig);
411 if (isolated_override) {
412 preconfig.isolated = isolated_override.value();
428 preconfig.utf8_mode =
true;
433 status = Py_PreInitialize(&preconfig);
444 bool has_python_executable =
false;
447 PyConfig_InitPythonConfig(&config);
452 PyConfig_InitIsolatedConfig(&config);
457 config.install_signal_handlers = 1;
460 if (isolated_override) {
461 config.isolated = isolated_override.value();
466 config.pathconfig_warnings = 0;
472 bool show_python_warnings =
false;
479 show_python_warnings =
true;
482 if (show_python_warnings) {
488 PyWideStringList_Append(&config.warnoptions,
L"default");
511 config.parse_argv = 0;
512 status = PyConfig_SetBytesArgv(&config, argc,
const_cast<char *
const *
>(argv));
522 status = PyConfig_SetBytesString(&config, &config.program_name, program_path);
531 program_path,
sizeof(program_path), PY_MAJOR_VERSION, PY_MINOR_VERSION))
533 status = PyConfig_SetBytesString(&config, &config.executable, program_path);
535 has_python_executable =
true;
540 "Unable to find the Python binary, "
541 "the multiprocessing module may not be functional!\n");
549 if (py_path_bundle.has_value()) {
555 if (strchr(py_path_bundle->c_str(),
':')) {
557 "Warning! Blender application is located in a path containing ':' or '/' chars\n"
558 "This may make Python import function fail\n");
562 status = PyConfig_SetBytesString(&config, &config.home, py_path_bundle->c_str());
565# ifdef PYTHON_SSL_CERT_FILE
567 const char *ssl_cert_file_env =
"SSL_CERT_FILE";
568 if (
BLI_getenv(ssl_cert_file_env) ==
nullptr) {
569 const char *ssl_cert_file_suffix = PYTHON_SSL_CERT_FILE;
572 ssl_cert_file,
sizeof(ssl_cert_file), py_path_bundle->c_str(), ssl_cert_file_suffix);
579# if defined(__APPLE__) || defined(_WIN32)
581 "Bundled Python not found and is expected on this platform "
582 "(the 'install' target may have not been built)\n");
588 status = Py_InitializeFromConfig(&config);
589 PyConfig_Clear(&config);
593 if (!has_python_executable) {
594 PySys_SetObject(
"executable", Py_None);
601 Py_DECREF(PyImport_ImportModule(
"threading"));
619#ifdef WITH_PYTHON_MODULE
622 struct _inittab *inittab_item;
623 PyObject *sys_modules = PyImport_GetModuleDict();
626 PyObject *
mod = inittab_item->initfunc();
628 PyDict_SetItemString(sys_modules, inittab_item->name,
mod);
646#ifndef WITH_PYTHON_MODULE
651 PyEval_ReleaseThread(PyGILState_GetThisThreadState());
655#ifdef WITH_PYTHON_MODULE
657 const char *imports[] = {
"atexit",
"addon_utils",
nullptr};
664#ifndef WITH_PYTHON_MODULE
665 BLI_assert_msg(Py_IsInitialized() != 0,
"Python must be initialized");
669 PyGILState_STATE gilstate = PyGILState_Ensure();
692#ifndef WITH_PYTHON_MODULE
696 if (do_python_exit) {
701 PyGILState_Release(gilstate);
702 (void)do_python_exit;
710 printf(
"tot exec: %d, ", bpy_timer_count);
711 printf(
"tot run: %.4fsec, ", bpy_timer_run_tot);
712 if (bpy_timer_count > 0) {
713 printf(
"average run: %.6fsec, ", (bpy_timer_run_tot / bpy_timer_count));
716 if (bpy_timer > 0.0) {
717 printf(
"tot usage %.4f%%", (bpy_timer_run_tot / bpy_timer) * 100.0);
726 BLI_assert_msg(Py_IsInitialized() != 0,
"Python must be initialized");
730 G.autoexec_fail[0] =
'\0';
770 fputs(
"\n# Python backtrace\n", fp);
776 PyFrameObject *frame = PyEval_GetFrame();
777 if (frame ==
nullptr) {
784 PyCodeObject *code = PyFrame_GetCode(frame);
785 const int line = PyFrame_GetLineNumber(frame);
786 const char *filepath = PyUnicode_AsUTF8(code->co_filename);
787 const char *funcname = PyUnicode_AsUTF8(code->co_name);
788 fprintf(fp,
" File \"%s\", line %d in %s\n", filepath, line, funcname);
790 PyFrameObject *frame_next = PyFrame_GetBack(frame);
798 const PyGILState_STATE gilstate = PyGILState_Ensure();
799 Py_DECREF((PyObject *)pyob_ptr);
800 PyGILState_Release(gilstate);
805 const PyGILState_STATE gilstate = PyGILState_Ensure();
806 const bool do_invalidate = (Py_REFCNT((PyObject *)pyob_ptr) > 1);
807 Py_DECREF((PyObject *)pyob_ptr);
811 PyGILState_Release(gilstate);
816 PyGILState_STATE gilstate;
821 if (bmain ==
nullptr) {
841 RPT_(
"Freestyle style module '%s'"),
842 module_conf.
script->id.name + 2);
849 for (text = bmain->
texts.first(); text; text =
static_cast<Text *
>(text->id.next)) {
856 printf(
"scripts disabled for \"%s\", skipping '%s'\n",
880 if (!(use_logging_info || use_logging_member)) {
885 const char *location = python_location ? python_location->c_str() :
"unknown:0";
887 if (use_logging_info) {
890 else if (use_logging_member) {
900 PyGILState_STATE gilstate;
903 gilstate = PyGILState_Ensure();
912 item = PyDict_GetItemString(pyctx, member);
914 if (item ==
nullptr) {
917 else if (item == Py_None) {
928 else if (PySequence_Check(item)) {
929 PyObject *seq_fast = PySequence_Fast(item,
"bpy_context_get sequence conversion");
930 if (seq_fast ==
nullptr) {
934 const int len = PySequence_Fast_GET_SIZE(seq_fast);
935 PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
938 for (i = 0; i <
len; i++) {
939 PyObject *list_item = seq_fast_items[i];
942 ptr = &
reinterpret_cast<BPy_StructRNA *
>(list_item)->ptr.value();
947 std::string message = std::string(
"'") + member +
948 "' list item not a valid type in sequence type '" +
949 Py_TYPE(list_item)->tp_name +
"'";
962 std::string message = std::string(
"'") + member +
"' not a valid type";
968 PyGILState_Release(gilstate);
980 if (!Py_IsInitialized()) {
984 PyGILState_STATE gilstate;
986 std::optional<std::string>
result = std::nullopt;
988 gilstate = PyGILState_Ensure();
1000 PyGILState_Release(gilstate);
1005#ifdef WITH_PYTHON_MODULE
1020static void main_python_exit_ensure();
1022static void bpy_detect_exit_singleton_cleanup(PyObject * )
1024 main_python_exit_ensure();
1027static void bpy_detect_exit_singleton_add_to_module(PyObject *
mod)
1029 static PyObject *singleton =
nullptr;
1036 const char *bpy_detect_exit_singleton_id =
"_bpy_detect_exit_singleton";
1037 if (singleton ==
nullptr) {
1040 void *pointer =
reinterpret_cast<void *
>(
uintptr_t(-1));
1041 singleton = PyCapsule_New(
1042 pointer, bpy_detect_exit_singleton_id, bpy_detect_exit_singleton_cleanup);
1046 Py_INCREF(singleton);
1048 PyModule_AddObject(
mod, bpy_detect_exit_singleton_id, singleton);
1055static void bpy_module_free(
void *
mod);
1058extern int main_python_enter(
int argc,
const char **argv);
1059extern void main_python_exit();
1061static void main_python_exit_ensure()
1063 static bool exit =
false;
1071static struct PyModuleDef bpy_proxy_def = {
1072 PyModuleDef_HEAD_INIT,
1090static void bpy_module_delay_init(PyObject *bpy_proxy)
1093 const char *argv[2];
1096 PyObject *filepath_obj = PyModule_GetFilenameObject(bpy_proxy);
1099 const char *filepath_rel = PyUnicode_AsUTF8(filepath_obj);
1100 char filepath_abs[1024];
1102 STRNCPY(filepath_abs, filepath_rel);
1104 Py_DECREF(filepath_obj);
1106 argv[0] = filepath_abs;
1109 main_python_enter(argc, argv);
1112 PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(
bpy_package_py));
1121 const char *bpy_modules_array[] = {
1128 PyObject *sys_modules = PyImport_GetModuleDict();
1129 for (
int i = 0; i <
ARRAY_SIZE(bpy_modules_array); i++) {
1130 PyObject *
mod = PyDict_GetItemString(sys_modules, bpy_modules_array[i]);
1132 bpy_detect_exit_singleton_add_to_module(
mod);
1141static bool bpy_module_ensure_compatible_version()
1147 const uint version_runtime = Py_Version;
1149 uint version_compile_major = PY_VERSION_HEX >> 24;
1150 uint version_compile_minor = ((PY_VERSION_HEX & 0x00ff0000) >> 16);
1151 uint version_runtime_major = version_runtime >> 24;
1152 uint version_runtime_minor = ((version_runtime & 0x00ff0000) >> 16);
1153 if ((version_compile_major != version_runtime_major) ||
1154 (version_compile_minor != version_runtime_minor))
1156 PyErr_Format(PyExc_ImportError,
1157 "The version of \"bpy\" was compiled with: "
1158 "(%u.%u) is incompatible with: (%u.%u) used by the interpreter!",
1159 version_compile_major,
1160 version_compile_minor,
1161 version_runtime_major,
1162 version_runtime_minor);
1168static void dealloc_obj_dealloc(PyObject *self);
1170static PyTypeObject dealloc_obj_Type;
1173static void dealloc_obj_dealloc(PyObject *self)
1175 bpy_module_delay_init(((dealloc_obj *)self)->
mod);
1179 dealloc_obj_Type.tp_free(self);
1182PyMODINIT_FUNC PyInit_bpy();
1184PyMODINIT_FUNC PyInit_bpy()
1186 if (!bpy_module_ensure_compatible_version()) {
1191 dealloc_obj_Type.tp_name =
"dealloc_obj";
1192 dealloc_obj_Type.tp_basicsize =
sizeof(dealloc_obj);
1193 dealloc_obj_Type.tp_dealloc = dealloc_obj_dealloc;
1194 dealloc_obj_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1196 if (PyType_Ready(&dealloc_obj_Type) < 0) {
1200 PyObject *bpy_proxy = PyModule_Create(&bpy_proxy_def);
1219 dob = (dealloc_obj *)dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
1220 dob->mod = bpy_proxy;
1221 PyModule_AddObject(bpy_proxy,
"__file__", (PyObject *)dob);
1226static void bpy_module_free(
void * )
1228 main_python_exit_ensure();
1236 const char *kwlist[] = {
1237 "False",
"None",
"True",
"and",
"as",
"assert",
"async",
"await",
"break",
1238 "class",
"continue",
"def",
"del",
"elif",
"else",
"except",
"finally",
"for",
1239 "from",
"global",
"if",
"import",
"in",
"is",
"lambda",
"nonlocal",
"not",
1240 "or",
"pass",
"raise",
"return",
"try",
"while",
"with",
"yield",
nullptr,
1243 for (
int i = 0; kwlist[i]; i++) {
#define BLI_path_join(...)
#define SNPRINTF_UTF8(dst, format,...)
Platform independent time functions.
#define CLOG_DEBUG(clg_ref,...)
#define CLOG_AT_LEVEL_NOCHECK(clg_ref, verbose_level,...)
#define CLOG_CHECK(clg_ref, verbose_level,...)
#define CLOG_INFO(clg_ref,...)
#define BLI_assert_unreachable()
#define BLI_assert_msg(a, msg)
#define BPy_StructRNA_Check(v)
VecBase< float, D > constexpr mod(VecOp< float, D >, VecOp< float, D >) RET
PyObject * Manta_initPython(void)
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
std::string filename(const std::string_view &str, size_t pos)
PyObject * BPyInit_idprop()
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static void bpy_context_log_member_error(const bContext *C, const char *message)
void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
bool PyC_IsInterpreterActive()
bool text_check_identifier(char ch)
void BPY_python_use_user_env()
void * CTX_py_dict_get(const bContext *C)
char * STRNCPY(char(&dst)[N], const char *src)
PyObject * BPY_rna_module()
void BPY_modules_update()
static bool py_use_user_env
PyMODINIT_FUNC PyInit_mathutils_noise()
void BPY_context_dict_clear_members_array(void **dict_p, void *dict_orig, const char *context_members[], uint context_members_len)
void BPY_python_backtrace(FILE *fp)
BPy_StructRNA * bpy_context_module
void pyrna_context_clear(bContext *C)
std::optional< std::string > BPY_python_current_file_and_line()
PyObject * BPyInit_bmesh()
void pyrna_context_init(bContext *C)
bool BPY_python_use_system_env_get()
bool BPY_string_is_keyword(const char *str)
void BPY_app_handlers_reset(bool do_all)
PyObject * bpy_package_py
bool text_check_identifier_nodigit(char ch)
void BPY_DECREF(void *pyob_ptr)
PyObject * BPyInit_bmesh_types()
bool CTX_member_logging_get(const bContext *C)
bool bool BPY_run_text(bContext *C, Text *text, ReportList *reports, bool do_jump) ATTR_NONNULL(1
void BPY_text_free_code(Text *text)
void PyC_FileAndNum_Safe(const char **r_filename, int *r_lineno)
void BPY_python_start(bContext *C, int argc, const char **argv)
CLG_LogRef * BKE_LOG_CONTEXT
void BLI_setenv(const char *env, const char *val) ATTR_NONNULL(1)
void BPY_context_set(bContext *C)
const char * BKE_main_blendfile_path(const Main *bmain) ATTR_NONNULL()
static bool bpy_context_set_ex(bContext *C, PyGILState_STATE *gilstate, const bool allow_null_context)
std::optional< std::string > BKE_appdir_folder_id(int folder_id, const char *subfolder) ATTR_WARN_UNUSED_RESULT
int text_check_identifier_nodigit_unicode(unsigned int ch)
PyMODINIT_FUNC PyInit_mathutils()
PyObject * BPyInit__bpy_path()
PyObject * BPyInit_imbuf()
struct bContext * BPY_context_get()
void CTX_data_type_set(bContextDataResult *result, ContextDataType type)
CLG_LogRef * BPY_LOG_INTERFACE
PyMODINIT_FUNC BPyInit_bl_math()
void CTX_data_pointer_set_ptr(bContextDataResult *result, const PointerRNA *ptr)
static bool py_use_system_env
void BPY_atexit_register()
bool BKE_appdir_program_python_search(char *program_filepath, size_t program_filepath_maxncpy, int version_major, int version_minor) ATTR_NONNULL(1)
bool BLI_path_abs_from_cwd(char *path, size_t path_maxncpy) ATTR_NONNULL(1)
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
void BPY_python_reset(bContext *C)
bool BPY_run_string_eval(bContext *C, const char *imports[], const char *expr)
PyObject * BPY_rna_types()
bool BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
void BPY_rna_props_clear_all()
bool bpy_context_set_allow_null(struct bContext *C, PyGILState_STATE *gilstate)
void BPY_app_translations_end()
int text_check_identifier_unicode(unsigned int ch)
void BPY_modules_load_user(bContext *C)
_W64 unsigned int uintptr_t
static void bpy_context_end(bContext *C)
void pyrna_invalidate(BPy_DummyPointerRNA *self)
static void pystatus_exit_on_error(const PyStatus &status)
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL
Main * CTX_data_main(const bContext *C)
PyObject * BPyInit_audaspace()
PyObject * BPyInit_hydra()
bool bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate) ATTR_NONNULL(1)
void BPy_init_modules(bContext *C)
static _inittab bpy_internal_modules[]
void BPY_python_end(bool do_python_exit)
PyMODINIT_FUNC PyInit_mathutils_kdtree()
void CTX_data_list_add_ptr(bContextDataResult *result, const PointerRNA *ptr)
double BLI_time_now_seconds()
PyObject * BPyInit_bmesh_geometry()
const char * BKE_appdir_program_path() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
PyMODINIT_FUNC PyInit_mathutils_geometry()
void * CCL_python_module_init()
void BPY_context_update(bContext *C)
void bpy_context_clear(struct bContext *C, const PyGILState_STATE *gilstate)
void BPY_atexit_unregister()
void BPY_python_use_system_env()
void CTX_wm_operator_poll_msg_clear(bContext *C)
void bpy_intern_string_exit()
CLG_LOGREF_DECLARE_GLOBAL(BKE_LOG_CONTEXT, "context")
const char * BLI_getenv(const char *env) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void bpy_intern_string_init()
void BPY_update_rna_module()
PyObject * BPyInit_bmesh_utils()
header-only compatibility defines.
#define PyThreadState_GetUnchecked
PyObject_HEAD std::optional< PointerRNA > ptr
ListBaseT< FreestyleModuleConfig > modules
ListBaseT< Scene > scenes
ListBaseT< ViewLayer > view_layers
struct FreestyleConfig freestyle_config