3
0

PythonSystemComponent.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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 (auto 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::AutoExpand, true)
  308. ;
  309. }
  310. }
  311. PythonActionManagerHandler::Reflect(context);
  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. // initialize internal base module and bootstrap scripts
  363. ExecuteByString("import azlmbr", false);
  364. ExecuteBootstrapScripts(pythonPathStack);
  365. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPostInitialize);
  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. AZStd::vector<AZ::IO::Path> gemSourcePaths;
  441. auto AppendGemPaths = [&gemSourcePaths](AZStd::string_view, AZStd::string_view gemPath)
  442. {
  443. gemSourcePaths.emplace_back(gemPath);
  444. };
  445. AZ::SettingsRegistryMergeUtils::VisitActiveGems(*settingsRegistry, AppendGemPaths);
  446. for (const AZ::IO::Path& gemSourcePath : gemSourcePaths)
  447. {
  448. resolveScriptPath(gemSourcePath.Native());
  449. }
  450. // 3 - project
  451. resolveScriptPath(AZStd::string_view{ projectPath });
  452. // 4 - user
  453. AZStd::string assetsType;
  454. AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, assetsType,
  455. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, AzFramework::AssetSystem::Assets);
  456. if (!assetsType.empty())
  457. {
  458. AZ::IO::FixedMaxPath userCachePath;
  459. if (settingsRegistry->Get(userCachePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_CacheRootFolder);
  460. !userCachePath.empty())
  461. {
  462. userCachePath /= "user";
  463. resolveScriptPath(userCachePath.Native());
  464. }
  465. }
  466. }
  467. void PythonSystemComponent::ExecuteBootstrapScripts(const PythonPathStack& pythonPathStack)
  468. {
  469. for(const auto& path : pythonPathStack)
  470. {
  471. AZStd::string bootstrapPath;
  472. AzFramework::StringFunc::Path::Join(path.c_str(), "bootstrap.py", bootstrapPath);
  473. if (AZ::IO::SystemFile::Exists(bootstrapPath.c_str()))
  474. {
  475. [[maybe_unused]] bool success = ExecuteByFilename(bootstrapPath);
  476. AZ_Assert(success, "Error while executing bootstrap script: %s", bootstrapPath.c_str());
  477. }
  478. }
  479. }
  480. bool PythonSystemComponent::StartPythonInterpreter(const PythonPathStack& pythonPathStack)
  481. {
  482. AZStd::unordered_set<AZStd::string> pyPackageSites(pythonPathStack.begin(), pythonPathStack.end());
  483. AZ::IO::FixedMaxPath engineRoot = AZ::Utils::GetEnginePath();
  484. // set PYTHON_HOME
  485. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, engineRoot.c_str());
  486. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  487. {
  488. AZ_Warning("python", false, "Python home path must exist! path:%s", pyBasePath.c_str());
  489. return false;
  490. }
  491. AZStd::wstring pyHomePath;
  492. AZStd::to_wstring(pyHomePath, pyBasePath);
  493. Py_SetPythonHome(pyHomePath.c_str());
  494. // display basic Python information
  495. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  496. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  497. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  498. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  499. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  500. try
  501. {
  502. // ignore system location for sites site-packages
  503. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  504. Py_IgnoreEnvironmentFlag = 1; // -E
  505. Py_InspectFlag = 1; // unhandled SystemExit will terminate the process unless Py_InspectFlag is set
  506. const bool initializeSignalHandlers = true;
  507. pybind11::initialize_interpreter(initializeSignalHandlers);
  508. // Add custom site packages after initializing the interpreter above. Calling Py_SetPath before initialization
  509. // 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
  510. if (pyPackageSites.size())
  511. {
  512. ExtendSysPath(pyPackageSites);
  513. }
  514. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  515. // Acquire GIL before calling Python code
  516. PythonGILScopedLock lock(m_lock, m_lockRecursiveCounter);
  517. if (EditorPythonBindings::PythonSymbolEventBus::GetTotalNumOfEventHandlers() == 0)
  518. {
  519. m_symbolLogHelper = AZStd::make_shared<PythonSystemComponent::SymbolLogHelper>();
  520. }
  521. // print Python version using AZ logging
  522. const int verRet = PyRun_SimpleStringFlags("import sys \nprint (sys.version) \n", nullptr);
  523. AZ_Error("python", verRet == 0, "Error trying to fetch the version number in Python!");
  524. return verRet == 0 && !PyErr_Occurred();
  525. }
  526. catch ([[maybe_unused]] const std::exception& e)
  527. {
  528. AZ_Warning("python", false, "Py_Initialize() failed with %s!", e.what());
  529. return false;
  530. }
  531. }
  532. bool PythonSystemComponent::ExtendSysPath(const AZStd::unordered_set<AZStd::string>& extendPaths)
  533. {
  534. AZStd::unordered_set<AZStd::string> oldPathSet;
  535. auto SplitPath = [&oldPathSet](AZStd::string_view pathPart)
  536. {
  537. oldPathSet.emplace(pathPart);
  538. };
  539. AZ::StringFunc::TokenizeVisitor(Py_EncodeLocale(Py_GetPath(), nullptr), SplitPath, DELIM);
  540. bool appended{ false };
  541. AZStd::string pathAppend{ "import sys\n" };
  542. for (const auto& thisStr : extendPaths)
  543. {
  544. if (!oldPathSet.contains(thisStr))
  545. {
  546. pathAppend.append(AZStd::string::format("sys.path.append(r'%s')\n", thisStr.c_str()));
  547. appended = true;
  548. }
  549. }
  550. if (appended)
  551. {
  552. ExecuteByString(pathAppend.c_str(), false);
  553. return true;
  554. }
  555. return false;
  556. }
  557. bool PythonSystemComponent::StopPythonInterpreter()
  558. {
  559. if (Py_IsInitialized())
  560. {
  561. RedirectOutput::Shutdown();
  562. pybind11::finalize_interpreter();
  563. }
  564. else
  565. {
  566. AZ_Warning("python", false, "Did not finalize since Py_IsInitialized() was false.");
  567. }
  568. return true;
  569. }
  570. void PythonSystemComponent::ExecuteByString(AZStd::string_view script, bool printResult)
  571. {
  572. if (!Py_IsInitialized())
  573. {
  574. AZ_Error("python", false, "Can not ExecuteByString() since the embeded Python VM is not ready.");
  575. return;
  576. }
  577. if (!script.empty())
  578. {
  579. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  580. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByString, script);
  581. // Acquire GIL before calling Python code
  582. PythonGILScopedLock lock(m_lock, m_lockRecursiveCounter);
  583. // Acquire scope for __main__ for executing our script
  584. pybind11::object scope = pybind11::module::import("__main__").attr("__dict__");
  585. bool shouldPrintValue = false;
  586. if (printResult)
  587. {
  588. // Attempt to compile our code to determine if it's an expression
  589. // i.e. a Python code object with only an rvalue
  590. // If it is, it can be evaled to produce a PyObject
  591. // If it's not, we can't evaluate it into a result and should fall back to exec
  592. shouldPrintValue = true;
  593. using namespace pybind11::literals;
  594. // codeop.compile_command is a thin wrapper around the Python compile builtin
  595. // We attempt to compile using symbol="eval" to see if the string is valid for eval
  596. // This is similar to what the Python REPL does internally
  597. pybind11::object codeop = pybind11::module::import("codeop");
  598. pybind11::object compileCommand = codeop.attr("compile_command");
  599. try
  600. {
  601. compileCommand(script.data(), "symbol"_a="eval");
  602. }
  603. catch (const pybind11::error_already_set&)
  604. {
  605. shouldPrintValue = false;
  606. }
  607. }
  608. try
  609. {
  610. if (shouldPrintValue)
  611. {
  612. // We're an expression, run and print the result
  613. pybind11::object result = pybind11::eval(script.data(), scope);
  614. pybind11::print(result);
  615. }
  616. else
  617. {
  618. // Just exec the code block
  619. pybind11::exec(script.data(), scope);
  620. }
  621. }
  622. catch (pybind11::error_already_set& pythonError)
  623. {
  624. // Release the exception stack and let Python print it to stderr
  625. pythonError.restore();
  626. PyErr_Print();
  627. }
  628. }
  629. }
  630. bool PythonSystemComponent::ExecuteByFilename(AZStd::string_view filename)
  631. {
  632. AZStd::vector<AZStd::string_view> args;
  633. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  634. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilename, filename);
  635. return ExecuteByFilenameWithArgs(filename, args);
  636. }
  637. bool PythonSystemComponent::ExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, const AZStd::vector<AZStd::string_view>& args)
  638. {
  639. AZ_TracePrintf("python", "Running automated test: %.*s (testcase %.*s)", AZ_STRING_ARG(filename), AZ_STRING_ARG(testCase))
  640. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  641. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilenameAsTest, filename, testCase, args);
  642. const Result evalResult = EvaluateFile(filename, args);
  643. return evalResult == Result::Okay;
  644. }
  645. bool PythonSystemComponent::ExecuteByFilenameWithArgs(AZStd::string_view filename, const AZStd::vector<AZStd::string_view>& args)
  646. {
  647. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  648. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilenameWithArgs, filename, args);
  649. const Result result = EvaluateFile(filename, args);
  650. return result == Result::Okay;
  651. }
  652. PythonSystemComponent::Result PythonSystemComponent::EvaluateFile(AZStd::string_view filename, const AZStd::vector<AZStd::string_view>& args)
  653. {
  654. if (!Py_IsInitialized())
  655. {
  656. AZ_Error("python", false, "Can not evaluate file since the embedded Python VM is not ready.");
  657. return Result::Error_IsNotInitialized;
  658. }
  659. if (filename.empty())
  660. {
  661. AZ_Error("python", false, "Invalid empty filename detected.");
  662. return Result::Error_InvalidFilename;
  663. }
  664. // support the alias version of a script such as @engroot@/Editor/Scripts/select_story_anim_objects.py
  665. AZStd::string theFilename(filename);
  666. {
  667. char resolvedPath[AZ_MAX_PATH_LEN] = { 0 };
  668. AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(theFilename.c_str(), resolvedPath, AZ_MAX_PATH_LEN);
  669. theFilename = resolvedPath;
  670. }
  671. if (!AZ::IO::FileIOBase::GetInstance()->Exists(theFilename.c_str()))
  672. {
  673. AZ_Error("python", false, "Missing Python file named (%s)", theFilename.c_str());
  674. return Result::Error_MissingFile;
  675. }
  676. FILE* file = nullptr;
  677. azfopen(&file, theFilename.c_str(), "rb");
  678. if (!file)
  679. {
  680. AZ_Error("python", false, "Missing Python file named (%s)", theFilename.c_str());
  681. return Result::Error_FileOpenValidation;
  682. }
  683. Result pythonScriptResult = Result::Okay;
  684. try
  685. {
  686. // Acquire GIL before calling Python code
  687. PythonGILScopedLock lock(m_lock, m_lockRecursiveCounter);
  688. // Create standard "argc" / "argv" command-line parameters to pass in to the Python script via sys.argv.
  689. // argc = number of parameters. This will always be at least 1, since the first parameter is the script name.
  690. // argv = the list of parameters, in wchar format.
  691. // Our expectation is that the args passed into this function does *not* already contain the script name.
  692. int argc = aznumeric_cast<int>(args.size()) + 1;
  693. // Note: This allocates from PyMem to ensure that Python has access to the memory.
  694. wchar_t** argv = static_cast<wchar_t**>(PyMem_Malloc(argc * sizeof(wchar_t*)));
  695. // Python 3.x is expecting wchar* strings for the command-line args.
  696. argv[0] = Py_DecodeLocale(theFilename.c_str(), nullptr);
  697. for (int arg = 0; arg < args.size(); arg++)
  698. {
  699. AZStd::string argString(args[arg]);
  700. argv[arg + 1] = Py_DecodeLocale(argString.c_str(), nullptr);
  701. }
  702. // Tell Python the command-line args.
  703. // Note that this has a side effect of adding the script's path to the set of directories checked for "import" commands.
  704. const int updatePath = 1;
  705. PySys_SetArgvEx(argc, argv, updatePath);
  706. PyCompilerFlags flags;
  707. flags.cf_flags = 0;
  708. const int bAutoCloseFile = true;
  709. const int returnCode = PyRun_SimpleFileExFlags(file, theFilename.c_str(), bAutoCloseFile, &flags);
  710. if (returnCode != 0)
  711. {
  712. AZStd::string message = AZStd::string::format("Detected script failure in Python script(%s); return code %d!", theFilename.c_str(), returnCode);
  713. AZ_Warning("python", false, message.c_str());
  714. using namespace AzToolsFramework;
  715. EditorPythonConsoleNotificationBus::Broadcast(&EditorPythonConsoleNotificationBus::Events::OnExceptionMessage, message.c_str());
  716. pythonScriptResult = Result::Error_PythonException;
  717. }
  718. // Free any memory allocated for the command-line args.
  719. for (int arg = 0; arg < argc; arg++)
  720. {
  721. PyMem_RawFree(argv[arg]);
  722. }
  723. PyMem_Free(argv);
  724. }
  725. catch ([[maybe_unused]] const std::exception& e)
  726. {
  727. AZ_Error("python", false, "Detected an internal exception %s while running script (%s)!", e.what(), theFilename.c_str());
  728. return Result::Error_InternalException;
  729. }
  730. return pythonScriptResult;
  731. }
  732. } // namespace EditorPythonBindings