| 39 | namespace openstudio { |
| 40 | |
| 41 | void addToPythonPath(const openstudio::path& includePath) { |
| 42 | |
| 43 | if (includePath.empty()) { |
| 44 | return; |
| 45 | } |
| 46 | |
| 47 | // fmt::print("Prepending '{}' to sys.path\n", includePath); |
| 48 | |
| 49 | PyObject* unicodeIncludePath = nullptr; |
| 50 | if constexpr (std::is_same_v<typename openstudio::path::value_type, wchar_t>) { |
| 51 | const std::wstring ws = includePath.generic_wstring(); |
| 52 | unicodeIncludePath = PyUnicode_FromWideChar(ws.c_str(), static_cast<Py_ssize_t>(ws.size())); // New reference |
| 53 | } else { |
| 54 | const std::string s = includePath.generic_string(); |
| 55 | unicodeIncludePath = PyUnicode_FromString(s.c_str()); // New reference |
| 56 | } |
| 57 | |
| 58 | if (unicodeIncludePath == nullptr) { |
| 59 | throw std::runtime_error(fmt::format("Unable to convert path '{}' for addition to sys.path in Python", includePath.generic_string())); |
| 60 | } |
| 61 | |
| 62 | PyObject* sysPath = PySys_GetObject("path"); // Borrowed reference |
| 63 | int ret = PyList_Insert(sysPath, 0, unicodeIncludePath); |
| 64 | Py_DECREF(unicodeIncludePath); |
| 65 | if (ret != 0) { |
| 66 | throw std::runtime_error(fmt::format("Unable to add path '{}' to the sys.path in Python", includePath.generic_string())); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | void PythonEngine::pyimport(const std::string& importName, const std::string& includePath) { |
| 71 | addToPythonPath(includePath); |
no test coverage detected