ScriptingEngine.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include <Python.h>
  2. #include "ScriptingEngine.h"
  3. #include "Exception.h"
  4. #include "Logger.h"
  5. extern "C" void initAnki(); /// Defined in BoostPythonInterfaces.cpp by boost::python
  6. //======================================================================================================================
  7. // init =
  8. //======================================================================================================================
  9. void ScriptingEngine::init()
  10. {
  11. INFO("Initializing scripting engine...");
  12. PyImport_AppendInittab((char*)("Anki"), &initAnki);
  13. Py_Initialize();
  14. mainModule = boost::python::object(boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("__main__"))));
  15. mainNamespace = mainModule.attr("__dict__");
  16. ankiModule = boost::python::object(boost::python::handle<>(PyImport_ImportModule("Anki")));
  17. INFO("Scripting engine initialized");
  18. }
  19. //======================================================================================================================
  20. // execScript =
  21. //======================================================================================================================
  22. void ScriptingEngine::execScript(const char* script, const char* scriptName)
  23. {
  24. try
  25. {
  26. boost::python::handle<>ignored(PyRun_String(script, Py_file_input, mainNamespace.ptr(), mainNamespace.ptr()));
  27. }
  28. catch(boost::python::error_already_set)
  29. {
  30. PyErr_Print();
  31. throw EXCEPTION("Script \"" + scriptName + "\" failed with error");
  32. }
  33. }