MCPcopy Create free account
hub / github.com/NatLabRockies/OpenStudio / addToPythonPath

Function addToPythonPath

python/engine/PythonEngine.cpp:41–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

39namespace openstudio {
40
41void 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
70void PythonEngine::pyimport(const std::string& importName, const std::string& includePath) {
71 addToPythonPath(includePath);

Callers 3

pyimportMethod · 0.85
setupPythonPathMethod · 0.85
PythonEngineMethod · 0.85

Calls 2

emptyMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected