knowrob  2.1.0
A Knowledge Base System for Cognition-enabled Robots
utils.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of KnowRob, please consult
3  * https://github.com/knowrob/knowrob for license details.
4  */
5 
6 #include <set>
7 #include <list>
8 #include "knowrob/integration/python/utils.h"
9 #include "knowrob/URI.h"
10 #include "knowrob/Logger.h"
11 
12 namespace knowrob::py {
13  std::string resolveModulePath(std::string_view modulePath) {
14  // guess if '/' or '.' is used as delimiter
15  if (modulePath.find('/') != std::string::npos) {
16  return URI::resolve(modulePath);
17  } else {
18  // replace '.' with '/', assuming dots do not appear in directory names.
19  std::string modulePath_withSlash(modulePath);
20  std::replace(modulePath_withSlash.begin(), modulePath_withSlash.end(), '.', '/');
21  return URI::resolve(modulePath_withSlash);
22  }
23  }
24 
25  std::string addToSysPath(const std::filesystem::path& modulePath) {
26  static std::set<std::filesystem::path> moduleDirectories;
27 
28  auto topmostPythonPath = modulePath.parent_path();
29  std::list<std::string> modulePathParts;
30  modulePathParts.push_front(modulePath.stem().string());
31  while(!topmostPythonPath.empty() && std::filesystem::exists(topmostPythonPath / "__init__.py")) {
32  modulePathParts.push_front(topmostPythonPath.stem().string());
33  topmostPythonPath = topmostPythonPath.parent_path();
34  }
35  std::stringstream ss;
36  for (auto it = modulePathParts.begin(); it != modulePathParts.end(); ++it) {
37  ss << *it;
38  if (it != --modulePathParts.end()) {
39  ss << ".";
40  }
41  }
42  auto relativeModulePath = ss.str();
43 
44  // make sure that the module directory is only added once
45  if (moduleDirectories.count(topmostPythonPath) == 0) {
46  moduleDirectories.insert(topmostPythonPath);
47  // >>> sys.path.append(moduleDir)
48  auto py_sys = boost::python::import("sys");
49  auto py_path = py_sys.attr("path");
50  auto sysPathAppend = py_path.attr("append");
51  sysPathAppend(topmostPythonPath.string());
52  KB_DEBUG("[python] Added '{}' to sys.path.", topmostPythonPath.string().c_str());
53  }
54 
55  return relativeModulePath;
56  }
57 }
#define KB_DEBUG
Definition: Logger.h:25
static std::string resolve(const std::string_view &uriString)
Definition: URI.cpp:79
TermRule & string()
Definition: terms.cpp:63
std::string addToSysPath(const std::filesystem::path &modulePath)
Definition: utils.cpp:25
std::string resolveModulePath(std::string_view modulePath)
Definition: utils.cpp:13