PythonEntry.cc 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <boost/foreach.hpp>
  2. #include <boost/format.hpp>
  3. #include <boost/python.hpp>
  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::Execute(std::string& main_fun)
  50. {
  51. std::string exec_string;
  52. if (!GetExecString(main_fun, exec_string))
  53. {
  54. LOG(WARNNING) << "no python exec string!";
  55. return;
  56. }
  57. try
  58. {
  59. boost::python::exec(exec_string.c_str(), main_ns_);
  60. }
  61. catch (...)
  62. {
  63. LOG(ERROR) << "python execute error";
  64. python_init_.PrintError();
  65. }
  66. }
  67. } // namespace Egametang