PythonEntry.cc 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <boost/foreach.hpp>
  2. #include <boost/format.hpp>
  3. #include "base/Marcos.h"
  4. #include "Python/PythonEntry.h"
  5. namespace Egametang {
  6. PythonEntry::PythonEntry():
  7. python_init_()
  8. {
  9. main_ns_ = import("__main__").attr("__dict__");
  10. }
  11. void PythonEntry::ImportPath(std::string& path)
  12. {
  13. python_paths_.insert(path);
  14. }
  15. void PythonEntry::ImportModule(std::string& module)
  16. {
  17. python_modules_.insert(module);
  18. }
  19. template <typename T>
  20. void PythonEntry::RegisterObjectPtr(std::string& name, T object_ptr)
  21. {
  22. main_ns_[name.c_str()] = object_ptr;
  23. }
  24. bool PythonEntry::GetExecString(const std::string& main_fun, std::string& exec_string)
  25. {
  26. exec_string = "import sys\n";
  27. boost::format format;
  28. if (python_paths_.size() == 0)
  29. {
  30. LOG(WARNNING) << "no python path";
  31. return false;
  32. }
  33. foreach(std::string& path, python_paths_)
  34. {
  35. exec_string += format("sys.path.append('%1%')\n") % path;
  36. }
  37. if (python_modules_.size() == 0)
  38. {
  39. LOG(WARNNING) << "no python module";
  40. return false;
  41. }
  42. foreach(std::string& module, python_modules_)
  43. {
  44. exec_string += format("import %1%\n") % module;
  45. }
  46. exec_string += main_fun;
  47. return true;
  48. }
  49. void PythonEntry::Exec(std::string& main_fun)
  50. {
  51. std::string exec_string;
  52. if (!GetExecString(main_fun, exec_string))
  53. {
  54. return;
  55. }
  56. try
  57. {
  58. boost::python::exec(exec_string.c_str(), main_ns_);
  59. }
  60. catch
  61. {
  62. LOG(ERROR) << "run python exec error";
  63. python_init.PrintError();
  64. }
  65. }
  66. } // namespace Egametang