PythonInterpreter.cc 1.4 KB

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