PythonSystemComponent.cpp 33 KB

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