PythonInterpreter.cc 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <boost/foreach.hpp>
  2. #include <boost/format.hpp>
  3. #include <boost/python.hpp>
  4. #include "Python/PythonInterpreter.h"
  5. namespace Egametang {
  6. PythonInterpreter::PythonInterpreter():
  7. python()
  8. {
  9. mainNS = boost::python::import("__main__").attr("__dict__");
  10. }
  11. void PythonInterpreter::ImportPath(std::string path)
  12. {
  13. paths.insert(path);
  14. }
  15. void PythonInterpreter::ImportModule(std::string module)
  16. {
  17. modules.insert(module);
  18. }
  19. bool PythonInterpreter::GetExecString(const std::string& main_fun, std::string& exec_string)
  20. {
  21. exec_string = "import sys\n";
  22. if (paths.size() == 0)
  23. {
  24. LOG(WARNING) << "no python path";
  25. return false;
  26. }
  27. foreach (std::string path, paths)
  28. {
  29. exec_string += boost::str(boost::format("sys.path.append('%1%')\n") % path);
  30. }
  31. if (modules.size() == 0)
  32. {
  33. LOG(WARNING) << "no python module";
  34. return false;
  35. }
  36. foreach (std::string module, modules)
  37. {
  38. exec_string += boost::str(boost::format("import %1%\n") % module);
  39. }
  40. exec_string += main_fun;
  41. return true;
  42. }
  43. void PythonInterpreter::Execute(std::string main_fun)
  44. {
  45. std::string exec_string;
  46. if (!GetExecString(main_fun, exec_string))
  47. {
  48. LOG(WARNING) << "no python exec string!";
  49. return;
  50. }
  51. try
  52. {
  53. boost::python::exec(exec_string.c_str(), mainNS);
  54. }
  55. catch (...)
  56. {
  57. LOG(ERROR) << "python execute error";
  58. python.PrintError();
  59. }
  60. }
  61. } // namespace Egametang