PythonBindings.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /*
  2. * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
  3. * its licensors.
  4. *
  5. * For complete copyright and license terms please see the LICENSE at the root of this
  6. * distribution (the "License"). All use of this software is governed by the License,
  7. * or, if provided, by the license below or the license accompanying this file. Do not
  8. * remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
  9. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. *
  11. */
  12. #include <PythonBindings.h>
  13. // Qt defines slots, which interferes with the use here.
  14. #pragma push_macro("slots")
  15. #undef slots
  16. #include <Python.h>
  17. #include <pybind11/functional.h>
  18. #include <pybind11/pybind11.h>
  19. #include <pybind11/embed.h>
  20. #include <pybind11/eval.h>
  21. #pragma pop_macro("slots")
  22. #include <AzCore/IO/FileIO.h>
  23. #include <AzCore/IO/SystemFile.h>
  24. #include <AzCore/std/string/conversions.h>
  25. #include <AzCore/StringFunc/StringFunc.h>
  26. namespace Platform
  27. {
  28. bool InsertPythonLibraryPath(
  29. AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot, const char* subPath)
  30. {
  31. // append lib path to Python paths
  32. AZ::IO::FixedMaxPath libPath = engineRoot;
  33. libPath /= AZ::IO::FixedMaxPathString::format(subPath, pythonPackage);
  34. libPath = libPath.LexicallyNormal();
  35. if (AZ::IO::SystemFile::Exists(libPath.c_str()))
  36. {
  37. paths.insert(libPath.c_str());
  38. return true;
  39. }
  40. AZ_Warning("python", false, "Python library path should exist. path:%s", libPath.c_str());
  41. return false;
  42. }
  43. // Implemented in each different platform's PAL implentation files, as it differs per platform.
  44. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  45. } // namespace Platform
  46. namespace O3DE::ProjectManager
  47. {
  48. PythonBindings::PythonBindings(const AZ::IO::PathView& enginePath)
  49. : m_enginePath(enginePath)
  50. {
  51. StartPython();
  52. }
  53. PythonBindings::~PythonBindings()
  54. {
  55. StopPython();
  56. }
  57. bool PythonBindings::StartPython()
  58. {
  59. if (Py_IsInitialized())
  60. {
  61. AZ_Warning("python", false, "Python is already active");
  62. return false;
  63. }
  64. // set PYTHON_HOME
  65. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, m_enginePath.c_str());
  66. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  67. {
  68. AZ_Warning("python", false, "Python home path must exist. path:%s", pyBasePath.c_str());
  69. return false;
  70. }
  71. AZStd::wstring pyHomePath;
  72. AZStd::to_wstring(pyHomePath, pyBasePath);
  73. Py_SetPythonHome(pyHomePath.c_str());
  74. // display basic Python information
  75. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  76. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  77. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  78. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  79. try
  80. {
  81. // ignore system location for sites site-packages
  82. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  83. Py_IgnoreEnvironmentFlag = 1; // -E
  84. const bool initializeSignalHandlers = true;
  85. pybind11::initialize_interpreter(initializeSignalHandlers);
  86. // Acquire GIL before calling Python code
  87. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  88. pybind11::gil_scoped_acquire acquire;
  89. // Setup sys.path
  90. int result = PyRun_SimpleString("import sys");
  91. AZ_Warning("ProjectManagerWindow", result != -1, "Import sys failed");
  92. result = PyRun_SimpleString(AZStd::string::format("sys.path.append('%s')", m_enginePath.c_str()).c_str());
  93. AZ_Warning("ProjectManagerWindow", result != -1, "Append to sys path failed");
  94. return result == 0 && !PyErr_Occurred();
  95. } catch ([[maybe_unused]] const std::exception& e)
  96. {
  97. AZ_Warning("python", false, "Py_Initialize() failed with %s", e.what());
  98. return false;
  99. }
  100. }
  101. bool PythonBindings::StopPython()
  102. {
  103. if (Py_IsInitialized())
  104. {
  105. pybind11::finalize_interpreter();
  106. }
  107. else
  108. {
  109. AZ_Warning("python", false, "Did not finalize since Py_IsInitialized() was false");
  110. }
  111. return !PyErr_Occurred();
  112. }
  113. void PythonBindings::ExecuteWithLock(AZStd::function<void()> executionCallback)
  114. {
  115. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  116. pybind11::gil_scoped_release release;
  117. pybind11::gil_scoped_acquire acquire;
  118. executionCallback();
  119. }
  120. ProjectInfo PythonBindings::GetCurrentProject()
  121. {
  122. ProjectInfo project;
  123. ExecuteWithLock([&] {
  124. auto currentProjectTool = pybind11::module::import("cmake.Tools.current_project");
  125. auto getCurrentProject = currentProjectTool.attr("get_current_project");
  126. auto currentProject = getCurrentProject(m_enginePath.c_str());
  127. project.m_path = currentProject.cast<std::string>().c_str();
  128. });
  129. return project;
  130. }
  131. }