diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index b93d4e406..f2e02c013 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -23,43 +23,31 @@ 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; -} +// the folders site.addsitepackages() puts on sys.path (python64 and python64\Lib\site-packages on Windows, +// lib/python3.x/site-packages elsewhere), the same way, but without running the .pth files in them. importing site +// doesn't run its main() when the interpreter was started without it +constexpr char const *site_packages_code = R"( +import os, site, sys +_known = {site.makepath(_path)[1] for _path in sys.path if _path} +for _folder in site.getsitepackages(): + if os.path.isdir(_folder): + _folder, _case = site.makepath(_folder) + if _case not in _known: + sys.path.append(_folder) + _known.add(_case) +)"; // 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); + PyObject *globals = PyDict_New(); + PyObject *result = globals != nullptr ? PyRun_String(site_packages_code, Py_file_input, globals, globals) : nullptr; + bool const added = result != nullptr; + Py_XDECREF(result); + Py_XDECREF(globals); PyErr_Clear(); - return result; + return added; } // 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