PythonSystemComponent.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project
  3. *
  4. * SPDX-License-Identifier: Apache-2.0 OR MIT
  5. *
  6. */
  7. #include <PythonSystemComponent.h>
  8. #include <EditorPythonBindings/EditorPythonBindingsBus.h>
  9. #include <Source/PythonCommon.h>
  10. #include <pybind11/pybind11.h>
  11. #include <pybind11/embed.h>
  12. #include <pybind11/eval.h>
  13. #include <osdefs.h> // for DELIM
  14. #include <AzCore/Component/EntityId.h>
  15. #include <AzCore/IO/SystemFile.h>
  16. #include <AzCore/Module/DynamicModuleHandle.h>
  17. #include <AzCore/Module/Module.h>
  18. #include <AzCore/Module/ModuleManagerBus.h>
  19. #include <AzCore/PlatformDef.h>
  20. #include <AzCore/Serialization/EditContext.h>
  21. #include <AzCore/Serialization/SerializeContext.h>
  22. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  23. #include <AzCore/std/string/conversions.h>
  24. #include <AzCore/StringFunc/StringFunc.h>
  25. #include <AzCore/Utils/Utils.h>
  26. #include <AzFramework/API/ApplicationAPI.h>
  27. #include <AzFramework/Asset/AssetSystemComponent.h>
  28. #include <AzFramework/IO/LocalFileIO.h>
  29. #include <AzFramework/CommandLine/CommandRegistrationBus.h>
  30. #include <AzFramework/StringFunc/StringFunc.h>
  31. #include <AzToolsFramework/API/EditorPythonConsoleBus.h>
  32. #include <AzToolsFramework/API/EditorPythonScriptNotificationsBus.h>
  33. namespace Platform
  34. {
  35. // Implemented in each different platform's implentation files, as it differs per platform.
  36. bool InsertPythonBinaryLibraryPaths(AZStd::unordered_set<AZStd::string>& paths, const char* pythonPackage, const char* engineRoot);
  37. AZStd::string GetPythonHomePath(const char* pythonPackage, const char* engineRoot);
  38. }
  39. // this is called the first time a Python script contains "import azlmbr"
  40. PYBIND11_EMBEDDED_MODULE(azlmbr, m)
  41. {
  42. EditorPythonBindings::EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindings::EditorPythonBindingsNotificationBus::Events::OnImportModule, m.ptr());
  43. }
  44. namespace RedirectOutput
  45. {
  46. using RedirectOutputFunc = AZStd::function<void(const char*)>;
  47. struct RedirectOutput
  48. {
  49. PyObject_HEAD
  50. RedirectOutputFunc write;
  51. };
  52. PyObject* RedirectWrite(PyObject* self, PyObject* args)
  53. {
  54. std::size_t written(0);
  55. RedirectOutput* selfimpl = reinterpret_cast<RedirectOutput*>(self);
  56. if (selfimpl->write)
  57. {
  58. char* data;
  59. if (!PyArg_ParseTuple(args, "s", &data))
  60. {
  61. return PyLong_FromSize_t(0);
  62. }
  63. selfimpl->write(data);
  64. written = strlen(data);
  65. }
  66. return PyLong_FromSize_t(written);
  67. }
  68. PyObject* RedirectFlush([[maybe_unused]] PyObject* self, [[maybe_unused]] PyObject* args)
  69. {
  70. // no-op
  71. return Py_BuildValue("");
  72. }
  73. PyMethodDef RedirectMethods[] =
  74. {
  75. {"write", RedirectWrite, METH_VARARGS, "sys.stdout.write"},
  76. {"flush", RedirectFlush, METH_VARARGS, "sys.stdout.flush"},
  77. {"write", RedirectWrite, METH_VARARGS, "sys.stderr.write"},
  78. {"flush", RedirectFlush, METH_VARARGS, "sys.stderr.flush"},
  79. {0, 0, 0, 0} // sentinel
  80. };
  81. PyTypeObject RedirectOutputType =
  82. {
  83. PyVarObject_HEAD_INIT(0, 0)
  84. "azlmbr_redirect.RedirectOutputType", // tp_name
  85. sizeof(RedirectOutput), /* tp_basicsize */
  86. 0, /* tp_itemsize */
  87. 0, /* tp_dealloc */
  88. 0, /* tp_print */
  89. 0, /* tp_getattr */
  90. 0, /* tp_setattr */
  91. 0, /* tp_reserved */
  92. 0, /* tp_repr */
  93. 0, /* tp_as_number */
  94. 0, /* tp_as_sequence */
  95. 0, /* tp_as_mapping */
  96. 0, /* tp_hash */
  97. 0, /* tp_call */
  98. 0, /* tp_str */
  99. 0, /* tp_getattro */
  100. 0, /* tp_setattro */
  101. 0, /* tp_as_buffer */
  102. Py_TPFLAGS_DEFAULT, /* tp_flags */
  103. "azlmbr_redirect objects", /* tp_doc */
  104. 0, /* tp_traverse */
  105. 0, /* tp_clear */
  106. 0, /* tp_richcompare */
  107. 0, /* tp_weaklistoffset */
  108. 0, /* tp_iter */
  109. 0, /* tp_iternext */
  110. RedirectMethods, /* tp_methods */
  111. 0, /* tp_members */
  112. 0, /* tp_getset */
  113. 0, /* tp_base */
  114. 0, /* tp_dict */
  115. 0, /* tp_descr_get */
  116. 0, /* tp_descr_set */
  117. 0, /* tp_dictoffset */
  118. 0, /* tp_init */
  119. 0, /* tp_alloc */
  120. 0 /* tp_new */
  121. };
  122. PyModuleDef RedirectOutputModule = { PyModuleDef_HEAD_INIT, "azlmbr_redirect", 0, -1, 0, };
  123. // Internal state
  124. PyObject* g_redirect_stdout = nullptr;
  125. PyObject* g_redirect_stdout_saved = nullptr;
  126. PyObject* g_redirect_stderr = nullptr;
  127. PyObject* g_redirect_stderr_saved = nullptr;
  128. PyMODINIT_FUNC PyInit_RedirectOutput(void)
  129. {
  130. g_redirect_stdout = nullptr;
  131. g_redirect_stdout_saved = nullptr;
  132. g_redirect_stderr = nullptr;
  133. g_redirect_stderr_saved = nullptr;
  134. RedirectOutputType.tp_new = PyType_GenericNew;
  135. if (PyType_Ready(&RedirectOutputType) < 0)
  136. {
  137. return 0;
  138. }
  139. PyObject* m = PyModule_Create(&RedirectOutputModule);
  140. if (m)
  141. {
  142. Py_INCREF(&RedirectOutputType);
  143. PyModule_AddObject(m, "Redirect", reinterpret_cast<PyObject*>(&RedirectOutputType));
  144. }
  145. return m;
  146. }
  147. void SetRedirection(const char* funcname, PyObject*& saved, PyObject*& current, RedirectOutputFunc func)
  148. {
  149. if (PyType_Ready(&RedirectOutputType) < 0)
  150. {
  151. AZ_Warning("python", false, "RedirectOutputType not ready!");
  152. return;
  153. }
  154. if (!current)
  155. {
  156. saved = PySys_GetObject(funcname); // borrowed
  157. current = RedirectOutputType.tp_new(&RedirectOutputType, 0, 0);
  158. }
  159. RedirectOutput* redirectOutput = reinterpret_cast<RedirectOutput*>(current);
  160. redirectOutput->write = func;
  161. PySys_SetObject(funcname, current);
  162. }
  163. void ResetRedirection(const char* funcname, PyObject*& saved, PyObject*& current)
  164. {
  165. if (current)
  166. {
  167. PySys_SetObject(funcname, saved);
  168. }
  169. Py_XDECREF(current);
  170. current = nullptr;
  171. }
  172. PyObject* s_RedirectModule = nullptr;
  173. void Intialize(PyObject* module)
  174. {
  175. using namespace AzToolsFramework;
  176. s_RedirectModule = module;
  177. SetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout, [](const char* msg)
  178. {
  179. EditorPythonConsoleNotificationBus::Broadcast(&EditorPythonConsoleNotificationBus::Events::OnTraceMessage, msg);
  180. });
  181. SetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr, [](const char* msg)
  182. {
  183. EditorPythonConsoleNotificationBus::Broadcast(&EditorPythonConsoleNotificationBus::Events::OnErrorMessage, msg);
  184. });
  185. PySys_WriteStdout("RedirectOutput installed");
  186. }
  187. void Shutdown()
  188. {
  189. ResetRedirection("stdout", g_redirect_stdout_saved, g_redirect_stdout);
  190. ResetRedirection("stderr", g_redirect_stderr_saved, g_redirect_stderr);
  191. Py_XDECREF(s_RedirectModule);
  192. s_RedirectModule = nullptr;
  193. }
  194. } // namespace RedirectOutput
  195. namespace EditorPythonBindings
  196. {
  197. void PythonSystemComponent::Reflect(AZ::ReflectContext* context)
  198. {
  199. if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
  200. {
  201. serialize->Class<PythonSystemComponent, AZ::Component>()
  202. ->Version(1)
  203. ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector<AZ::Crc32>{AZ_CRC_CE("AssetBuilder")})
  204. ;
  205. if (AZ::EditContext* ec = serialize->GetEditContext())
  206. {
  207. ec->Class<PythonSystemComponent>("PythonSystemComponent", "The Python interpreter")
  208. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  209. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System"))
  210. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  211. ;
  212. }
  213. }
  214. }
  215. void PythonSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  216. {
  217. provided.push_back(PythonEmbeddedService);
  218. }
  219. void PythonSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  220. {
  221. incompatible.push_back(PythonEmbeddedService);
  222. }
  223. void PythonSystemComponent::Activate()
  224. {
  225. AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Register(this);
  226. AzToolsFramework::EditorPythonRunnerRequestBus::Handler::BusConnect();
  227. }
  228. void PythonSystemComponent::Deactivate()
  229. {
  230. AzToolsFramework::EditorPythonRunnerRequestBus::Handler::BusDisconnect();
  231. AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Unregister(this);
  232. StopPython(true);
  233. }
  234. bool PythonSystemComponent::StartPython([[maybe_unused]] bool silenceWarnings)
  235. {
  236. struct ReleaseInitalizeWaiterScope final
  237. {
  238. using ReleaseFunction = AZStd::function<void(void)>;
  239. ReleaseInitalizeWaiterScope(ReleaseFunction releaseFunction)
  240. {
  241. m_releaseFunction = AZStd::move(releaseFunction);
  242. }
  243. ~ReleaseInitalizeWaiterScope()
  244. {
  245. m_releaseFunction();
  246. }
  247. ReleaseFunction m_releaseFunction;
  248. };
  249. ReleaseInitalizeWaiterScope scope([this]()
  250. {
  251. m_initalizeWaiter.release(m_initalizeWaiterCount);
  252. m_initalizeWaiterCount = 0;
  253. });
  254. if (Py_IsInitialized())
  255. {
  256. AZ_Warning("python", silenceWarnings, "Python is already active!");
  257. return false;
  258. }
  259. PythonPathStack pythonPathStack;
  260. DiscoverPythonPaths(pythonPathStack);
  261. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPreInitialize);
  262. if (StartPythonInterpreter(pythonPathStack))
  263. {
  264. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPostInitialize);
  265. // initialize internal base module and bootstrap scripts
  266. ExecuteByString("import azlmbr", false);
  267. ExecuteBootstrapScripts(pythonPathStack);
  268. return true;
  269. }
  270. return false;
  271. }
  272. bool PythonSystemComponent::StopPython([[maybe_unused]] bool silenceWarnings)
  273. {
  274. if (!Py_IsInitialized())
  275. {
  276. AZ_Warning("python", silenceWarnings, "Python is not active!");
  277. return false;
  278. }
  279. bool result = false;
  280. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPreFinalize);
  281. AzToolsFramework::EditorPythonRunnerRequestBus::Handler::BusDisconnect();
  282. result = StopPythonInterpreter();
  283. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPostFinalize);
  284. return result;
  285. }
  286. void PythonSystemComponent::WaitForInitialization()
  287. {
  288. m_initalizeWaiterCount++;
  289. m_initalizeWaiter.acquire();
  290. }
  291. void PythonSystemComponent::ExecuteWithLock(AZStd::function<void()> executionCallback)
  292. {
  293. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  294. pybind11::gil_scoped_release release;
  295. pybind11::gil_scoped_acquire acquire;
  296. executionCallback();
  297. }
  298. void PythonSystemComponent::DiscoverPythonPaths(PythonPathStack& pythonPathStack)
  299. {
  300. // the order of the Python paths is the order the Python bootstrap scripts will execute
  301. auto settingsRegistry = AZ::SettingsRegistry::Get();
  302. if (!settingsRegistry)
  303. {
  304. return;
  305. }
  306. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  307. if (projectPath.empty())
  308. {
  309. return;
  310. }
  311. auto resolveScriptPath = [&pythonPathStack](AZStd::string_view path)
  312. {
  313. auto editorScriptsPath = AZ::IO::Path(path) / "Editor" / "Scripts";
  314. if (AZ::IO::SystemFile::Exists(editorScriptsPath.c_str()))
  315. {
  316. pythonPathStack.emplace_back(AZStd::move(editorScriptsPath.LexicallyNormal().Native()));
  317. }
  318. };
  319. // The discovery order will be:
  320. // 1 - engine-root/EngineAsets
  321. // 2 - gems
  322. // 3 - project
  323. // 4 - user(dev)
  324. // 1 - engine
  325. AZ::IO::FixedMaxPath engineRoot;
  326. if (settingsRegistry->Get(engineRoot.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); !engineRoot.empty())
  327. {
  328. resolveScriptPath((engineRoot / "Assets").Native());
  329. }
  330. // 2 - gems
  331. struct GetGemSourcePathsVisitor
  332. : AZ::SettingsRegistryInterface::Visitor
  333. {
  334. GetGemSourcePathsVisitor(AZ::SettingsRegistryInterface& settingsRegistry)
  335. : m_settingsRegistry(settingsRegistry)
  336. {}
  337. void Visit(AZStd::string_view path, AZStd::string_view, AZ::SettingsRegistryInterface::Type,
  338. AZStd::string_view value) override
  339. {
  340. AZStd::string_view jsonSourcePathPointer{ path };
  341. // Remove the array index from the path and check if the JSON path ends with "/SourcePaths"
  342. AZ::StringFunc::TokenizeLast(jsonSourcePathPointer, "/");
  343. if (jsonSourcePathPointer.ends_with("/SourcePaths"))
  344. {
  345. AZ::IO::Path newSourcePath = jsonSourcePathPointer;
  346. // Resolve any file aliases first - Do not use ResolvePath() as that assumes
  347. // any relative path is underneath the @assets@ alias
  348. if (auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); fileIoBase != nullptr)
  349. {
  350. AZ::IO::FixedMaxPath replacedAliasPath;
  351. if (fileIoBase->ReplaceAlias(replacedAliasPath, value))
  352. {
  353. newSourcePath = AZ::IO::PathView(replacedAliasPath);
  354. }
  355. }
  356. // The current assumption is that the gem source path is the relative to the engine root
  357. AZ::IO::Path engineRootPath;
  358. m_settingsRegistry.Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  359. newSourcePath = (engineRootPath / newSourcePath).LexicallyNormal();
  360. if (auto gemSourcePathIter = AZStd::find(m_gemSourcePaths.begin(), m_gemSourcePaths.end(), newSourcePath);
  361. gemSourcePathIter == m_gemSourcePaths.end())
  362. {
  363. m_gemSourcePaths.emplace_back(AZStd::move(newSourcePath));
  364. }
  365. }
  366. }
  367. AZStd::vector<AZ::IO::Path> m_gemSourcePaths;
  368. private:
  369. AZ::SettingsRegistryInterface& m_settingsRegistry;
  370. };
  371. GetGemSourcePathsVisitor visitor{ *settingsRegistry };
  372. constexpr auto gemListKey = AZ::SettingsRegistryInterface::FixedValueString(AZ::SettingsRegistryMergeUtils::OrganizationRootKey)
  373. + "/Gems";
  374. settingsRegistry->Visit(visitor, gemListKey);
  375. for (const AZ::IO::Path& gemSourcePath : visitor.m_gemSourcePaths)
  376. {
  377. resolveScriptPath(gemSourcePath.Native());
  378. }
  379. // 3 - project
  380. resolveScriptPath(AZStd::string_view{ projectPath });
  381. // 4 - user
  382. AZStd::string assetsType;
  383. AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, assetsType,
  384. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, AzFramework::AssetSystem::Assets);
  385. if (!assetsType.empty())
  386. {
  387. AZ::IO::FixedMaxPath userCachePath;
  388. if (settingsRegistry->Get(userCachePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_CacheRootFolder);
  389. !userCachePath.empty())
  390. {
  391. userCachePath /= "user";
  392. resolveScriptPath(userCachePath.Native());
  393. }
  394. }
  395. }
  396. void PythonSystemComponent::ExecuteBootstrapScripts(const PythonPathStack& pythonPathStack)
  397. {
  398. for(const auto& path : pythonPathStack)
  399. {
  400. AZStd::string bootstrapPath;
  401. AzFramework::StringFunc::Path::Join(path.c_str(), "bootstrap.py", bootstrapPath);
  402. if (AZ::IO::SystemFile::Exists(bootstrapPath.c_str()))
  403. {
  404. ExecuteByFilename(bootstrapPath);
  405. }
  406. }
  407. }
  408. bool PythonSystemComponent::StartPythonInterpreter(const PythonPathStack& pythonPathStack)
  409. {
  410. AZStd::unordered_set<AZStd::string> pyPackageSites(pythonPathStack.begin(), pythonPathStack.end());
  411. const char* engineRoot = nullptr;
  412. AzFramework::ApplicationRequests::Bus::BroadcastResult(engineRoot, &AzFramework::ApplicationRequests::GetEngineRoot);
  413. // set PYTHON_HOME
  414. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, engineRoot);
  415. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  416. {
  417. AZ_Warning("python", false, "Python home path must exist! path:%s", pyBasePath.c_str());
  418. return false;
  419. }
  420. AZStd::wstring pyHomePath;
  421. AZStd::to_wstring(pyHomePath, pyBasePath);
  422. Py_SetPythonHome(pyHomePath.c_str());
  423. // display basic Python information
  424. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  425. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  426. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  427. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  428. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  429. try
  430. {
  431. // ignore system location for sites site-packages
  432. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  433. Py_IgnoreEnvironmentFlag = 1; // -E
  434. Py_InspectFlag = 1; // unhandled SystemExit will terminate the process unless Py_InspectFlag is set
  435. const bool initializeSignalHandlers = true;
  436. pybind11::initialize_interpreter(initializeSignalHandlers);
  437. // Add custom site packages after initializing the interpreter above. Calling Py_SetPath before initialization
  438. // alters the behavior of the initializer to not compute default search paths. See https://docs.python.org/3/c-api/init.html#c.Py_SetPath
  439. if (pyPackageSites.size())
  440. {
  441. ExtendSysPath(pyPackageSites);
  442. }
  443. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  444. // Acquire GIL before calling Python code
  445. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  446. pybind11::gil_scoped_acquire acquire;
  447. // print Python version using AZ logging
  448. const int verRet = PyRun_SimpleStringFlags("import sys \nprint (sys.version) \n", nullptr);
  449. AZ_Error("python", verRet == 0, "Error trying to fetch the version number in Python!");
  450. return verRet == 0 && !PyErr_Occurred();
  451. }
  452. catch ([[maybe_unused]] const std::exception& e)
  453. {
  454. AZ_Warning("python", false, "Py_Initialize() failed with %s!", e.what());
  455. return false;
  456. }
  457. }
  458. bool PythonSystemComponent::ExtendSysPath(const AZStd::unordered_set<AZStd::string>& extendPaths)
  459. {
  460. AZStd::unordered_set<AZStd::string> oldPathSet;
  461. auto SplitPath = [&oldPathSet](AZStd::string_view pathPart)
  462. {
  463. oldPathSet.emplace(pathPart);
  464. };
  465. AZ::StringFunc::TokenizeVisitor(Py_EncodeLocale(Py_GetPath(), nullptr), SplitPath, DELIM);
  466. bool appended{ false };
  467. AZStd::string pathAppend{ "import sys\n" };
  468. for (const auto& thisStr : extendPaths)
  469. {
  470. if (!oldPathSet.contains(thisStr))
  471. {
  472. pathAppend.append(AZStd::string::format("sys.path.append(r'%s')\n", thisStr.c_str()));
  473. appended = true;
  474. }
  475. }
  476. if (appended)
  477. {
  478. ExecuteByString(pathAppend.c_str(), false);
  479. return true;
  480. }
  481. return false;
  482. }
  483. bool PythonSystemComponent::StopPythonInterpreter()
  484. {
  485. if (Py_IsInitialized())
  486. {
  487. RedirectOutput::Shutdown();
  488. pybind11::finalize_interpreter();
  489. }
  490. else
  491. {
  492. AZ_Warning("python", false, "Did not finalize since Py_IsInitialized() was false.");
  493. }
  494. return !PyErr_Occurred();
  495. }
  496. void PythonSystemComponent::ExecuteByString(AZStd::string_view script, bool printResult)
  497. {
  498. if (!Py_IsInitialized())
  499. {
  500. AZ_Error("python", false, "Can not ExecuteByString() since the embeded Python VM is not ready.");
  501. return;
  502. }
  503. if (!script.empty())
  504. {
  505. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  506. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByString, script);
  507. // Acquire GIL before calling Python code
  508. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  509. pybind11::gil_scoped_acquire acquire;
  510. // Acquire scope for __main__ for executing our script
  511. pybind11::object scope = pybind11::module::import("__main__").attr("__dict__");
  512. bool shouldPrintValue = false;
  513. if (printResult)
  514. {
  515. // Attempt to compile our code to determine if it's an expression
  516. // i.e. a Python code object with only an rvalue
  517. // If it is, it can be evaled to produce a PyObject
  518. // If it's not, we can't evaluate it into a result and should fall back to exec
  519. shouldPrintValue = true;
  520. using namespace pybind11::literals;
  521. // codeop.compile_command is a thin wrapper around the Python compile builtin
  522. // We attempt to compile using symbol="eval" to see if the string is valid for eval
  523. // This is similar to what the Python REPL does internally
  524. pybind11::object codeop = pybind11::module::import("codeop");
  525. pybind11::object compileCommand = codeop.attr("compile_command");
  526. try
  527. {
  528. compileCommand(script.data(), "symbol"_a="eval");
  529. }
  530. catch (const pybind11::error_already_set&)
  531. {
  532. shouldPrintValue = false;
  533. }
  534. }
  535. try
  536. {
  537. if (shouldPrintValue)
  538. {
  539. // We're an expression, run and print the result
  540. pybind11::object result = pybind11::eval(script.data(), scope);
  541. pybind11::print(result);
  542. }
  543. else
  544. {
  545. // Just exec the code block
  546. pybind11::exec(script.data(), scope);
  547. }
  548. }
  549. catch (pybind11::error_already_set& pythonError)
  550. {
  551. // Release the exception stack and let Python print it to stderr
  552. pythonError.restore();
  553. PyErr_Print();
  554. }
  555. }
  556. }
  557. void PythonSystemComponent::ExecuteByFilename(AZStd::string_view filename)
  558. {
  559. AZStd::vector<AZStd::string_view> args;
  560. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  561. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilename, filename);
  562. ExecuteByFilenameWithArgs(filename, args);
  563. }
  564. void PythonSystemComponent::ExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, const AZStd::vector<AZStd::string_view>& args)
  565. {
  566. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  567. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilenameAsTest, filename, testCase, args);
  568. const Result evalResult = EvaluateFile(filename, args);
  569. if (evalResult == Result::Okay)
  570. {
  571. // all good, the test script will need to exit the application now
  572. return;
  573. }
  574. else
  575. {
  576. // something went wrong with executing the test script
  577. AZ::Debug::Trace::Terminate(0xF);
  578. }
  579. }
  580. void PythonSystemComponent::ExecuteByFilenameWithArgs(AZStd::string_view filename, const AZStd::vector<AZStd::string_view>& args)
  581. {
  582. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  583. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilenameWithArgs, filename, args);
  584. EvaluateFile(filename, args);
  585. }
  586. PythonSystemComponent::Result PythonSystemComponent::EvaluateFile(AZStd::string_view filename, const AZStd::vector<AZStd::string_view>& args)
  587. {
  588. if (!Py_IsInitialized())
  589. {
  590. AZ_Error("python", false, "Can not evaluate file since the embedded Python VM is not ready.");
  591. return Result::Error_IsNotInitialized;
  592. }
  593. if (filename.empty())
  594. {
  595. AZ_Error("python", false, "Invalid empty filename detected.");
  596. return Result::Error_InvalidFilename;
  597. }
  598. // support the alias version of a script such as @devroot@/Editor/Scripts/select_story_anim_objects.py
  599. AZStd::string theFilename(filename);
  600. {
  601. char resolvedPath[AZ_MAX_PATH_LEN] = { 0 };
  602. AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(theFilename.c_str(), resolvedPath, AZ_MAX_PATH_LEN);
  603. theFilename = resolvedPath;
  604. }
  605. if (!AZ::IO::FileIOBase::GetInstance()->Exists(theFilename.c_str()))
  606. {
  607. AZ_Error("python", false, "Missing Python file named (%s)", theFilename.c_str());
  608. return Result::Error_MissingFile;
  609. }
  610. FILE* file = _Py_fopen(theFilename.data(), "rb");
  611. if (!file)
  612. {
  613. AZ_Error("python", false, "Missing Python file named (%s)", theFilename.c_str());
  614. return Result::Error_FileOpenValidation;
  615. }
  616. Result pythonScriptResult = Result::Okay;
  617. try
  618. {
  619. // Acquire GIL before calling Python code
  620. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  621. pybind11::gil_scoped_acquire acquire;
  622. // Create standard "argc" / "argv" command-line parameters to pass in to the Python script via sys.argv.
  623. // argc = number of parameters. This will always be at least 1, since the first parameter is the script name.
  624. // argv = the list of parameters, in wchar format.
  625. // Our expectation is that the args passed into this function does *not* already contain the script name.
  626. int argc = aznumeric_cast<int>(args.size()) + 1;
  627. // Note: This allocates from PyMem to ensure that Python has access to the memory.
  628. wchar_t** argv = static_cast<wchar_t**>(PyMem_Malloc(argc * sizeof(wchar_t*)));
  629. // Python 3.x is expecting wchar* strings for the command-line args.
  630. argv[0] = Py_DecodeLocale(theFilename.c_str(), nullptr);
  631. for (int arg = 0; arg < args.size(); arg++)
  632. {
  633. AZStd::string argString(args[arg]);
  634. argv[arg + 1] = Py_DecodeLocale(argString.c_str(), nullptr);
  635. }
  636. // Tell Python the command-line args.
  637. // Note that this has a side effect of adding the script's path to the set of directories checked for "import" commands.
  638. const int updatePath = 1;
  639. PySys_SetArgvEx(argc, argv, updatePath);
  640. PyCompilerFlags flags;
  641. flags.cf_flags = 0;
  642. const int bAutoCloseFile = true;
  643. const int returnCode = PyRun_SimpleFileExFlags(file, theFilename.c_str(), bAutoCloseFile, &flags);
  644. if (returnCode != 0)
  645. {
  646. AZStd::string message = AZStd::string::format("Detected script failure in Python script(%s); return code %d!", theFilename.c_str(), returnCode);
  647. AZ_Warning("python", false, message.c_str());
  648. using namespace AzToolsFramework;
  649. EditorPythonConsoleNotificationBus::Broadcast(&EditorPythonConsoleNotificationBus::Events::OnExceptionMessage, message.c_str());
  650. pythonScriptResult = Result::Error_PythonException;
  651. }
  652. // Free any memory allocated for the command-line args.
  653. for (int arg = 0; arg < argc; arg++)
  654. {
  655. PyMem_RawFree(argv[arg]);
  656. }
  657. PyMem_Free(argv);
  658. }
  659. catch ([[maybe_unused]] const std::exception& e)
  660. {
  661. AZ_Error("python", false, "Detected an internal exception %s while running script (%s)!", e.what(), theFilename.c_str());
  662. return Result::Error_InternalException;
  663. }
  664. return pythonScriptResult;
  665. }
  666. } // namespace EditorPythonBindings