diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index 876934d4a..b93d4e406 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -23,6 +23,45 @@ http://mozilla.org/MPL/2.0/. namespace { +// appends the item to the list unless it's there already. false on a Python error +auto append_once(PyObject *List, PyObject *Item) -> bool +{ + int const contained = PySequence_Contains(List, Item); + if (contained != 0) + { + return contained > 0; + } + return PyList_Append(List, Item) == 0; +} + +// appends the folders of the installed packages (site-packages) of the interpreter to sys.path, as the site module does, +// but without running the .pth files in them. returns false when they couldn't be told or added +auto add_site_packages() -> bool +{ + PyObject *syspath = PySys_GetObject("path"); // borrowed ref + PyObject *sysconfig = PyImport_ImportModule("sysconfig"); + if (syspath == nullptr || sysconfig == nullptr) + { + Py_XDECREF(sysconfig); + PyErr_Clear(); + return false; + } + bool result = true; + for (char const *scheme : {"purelib", "platlib"}) + { + PyObject *folder = PyObject_CallMethod(sysconfig, "get_path", "s", scheme); + // the two are the same folder on Windows; a folder is added once + if (folder == nullptr || false == append_once(syspath, folder)) + { + result = false; + } + Py_XDECREF(folder); + } + Py_DECREF(sysconfig); + PyErr_Clear(); + return result; +} + // the file a script is in, looked for in the path given and then in python/local, and its text. no file name when there's none auto read_script(std::string_view File, std::string_view Path) -> std::pair { @@ -352,6 +391,10 @@ auto python_taskqueue::init() -> bool PyConfig config; PyConfig_InitPythonConfig(&config); config.install_signal_handlers = 0; // matches former Py_InitializeEx(0) + // no site module: besides putting site-packages on sys.path it runs every .pth file there, and those an older + // install left in the game folder (easy-install.pth of a Python 2.7 one) put its Pillow ahead of the one the game + // comes with, so the import failed and no screen was drawn. add_site_packages() puts the folders on sys.path instead + config.site_import = 0; PyStatus status = PyConfig_SetString(&config, &config.home, pythonhome); if (PyStatus_Exception(status)) @@ -376,6 +419,11 @@ auto python_taskqueue::init() -> bool PyConfig_Clear(&config); } + if (false == add_site_packages()) + { + ErrorLog("Python Interpreter: failed to add the site-packages folders to sys.path"); + } + // make CWD-local packages (e.g. the asset-side "scripts" package used by // texture/screen renderers) importable. Embedded CPython builds sys.path // from PYTHONHOME only; unlike the python CLI it does not prepend the