PythonSystemComponent.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. void PythonSystemComponent::Reflect(AZ::ReflectContext* context)
  229. {
  230. if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
  231. {
  232. serialize->Class<PythonSystemComponent, AZ::Component>()
  233. ->Version(1)
  234. ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector<AZ::Crc32>{AZ_CRC_CE("AssetBuilder")})
  235. ;
  236. if (AZ::EditContext* ec = serialize->GetEditContext())
  237. {
  238. ec->Class<PythonSystemComponent>("PythonSystemComponent", "The Python interpreter")
  239. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  240. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System"))
  241. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  242. ;
  243. }
  244. }
  245. }
  246. void PythonSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  247. {
  248. provided.push_back(PythonEmbeddedService);
  249. }
  250. void PythonSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  251. {
  252. incompatible.push_back(PythonEmbeddedService);
  253. }
  254. void PythonSystemComponent::Activate()
  255. {
  256. AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Register(this);
  257. AzToolsFramework::EditorPythonRunnerRequestBus::Handler::BusConnect();
  258. }
  259. void PythonSystemComponent::Deactivate()
  260. {
  261. AzToolsFramework::EditorPythonRunnerRequestBus::Handler::BusDisconnect();
  262. AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Unregister(this);
  263. StopPython(true);
  264. }
  265. bool PythonSystemComponent::StartPython([[maybe_unused]] bool silenceWarnings)
  266. {
  267. struct ReleaseInitalizeWaiterScope final
  268. {
  269. using ReleaseFunction = AZStd::function<void(void)>;
  270. ReleaseInitalizeWaiterScope(ReleaseFunction releaseFunction)
  271. {
  272. m_releaseFunction = AZStd::move(releaseFunction);
  273. }
  274. ~ReleaseInitalizeWaiterScope()
  275. {
  276. m_releaseFunction();
  277. }
  278. ReleaseFunction m_releaseFunction;
  279. };
  280. ReleaseInitalizeWaiterScope scope([this]()
  281. {
  282. m_initalizeWaiter.release(m_initalizeWaiterCount);
  283. m_initalizeWaiterCount = 0;
  284. });
  285. if (Py_IsInitialized())
  286. {
  287. AZ_Warning("python", silenceWarnings, "Python is already active!");
  288. return false;
  289. }
  290. PythonPathStack pythonPathStack;
  291. DiscoverPythonPaths(pythonPathStack);
  292. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPreInitialize);
  293. if (StartPythonInterpreter(pythonPathStack))
  294. {
  295. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPostInitialize);
  296. // initialize internal base module and bootstrap scripts
  297. ExecuteByString("import azlmbr", false);
  298. ExecuteBootstrapScripts(pythonPathStack);
  299. return true;
  300. }
  301. return false;
  302. }
  303. bool PythonSystemComponent::StopPython([[maybe_unused]] bool silenceWarnings)
  304. {
  305. if (!Py_IsInitialized())
  306. {
  307. AZ_Warning("python", silenceWarnings, "Python is not active!");
  308. return false;
  309. }
  310. bool result = false;
  311. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPreFinalize);
  312. AzToolsFramework::EditorPythonRunnerRequestBus::Handler::BusDisconnect();
  313. result = StopPythonInterpreter();
  314. EditorPythonBindingsNotificationBus::Broadcast(&EditorPythonBindingsNotificationBus::Events::OnPostFinalize);
  315. return result;
  316. }
  317. bool PythonSystemComponent::IsPythonActive()
  318. {
  319. return Py_IsInitialized() != 0;
  320. }
  321. void PythonSystemComponent::WaitForInitialization()
  322. {
  323. m_initalizeWaiterCount++;
  324. m_initalizeWaiter.acquire();
  325. }
  326. void PythonSystemComponent::ExecuteWithLock(AZStd::function<void()> executionCallback)
  327. {
  328. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  329. pybind11::gil_scoped_release release;
  330. pybind11::gil_scoped_acquire acquire;
  331. executionCallback();
  332. }
  333. void PythonSystemComponent::DiscoverPythonPaths(PythonPathStack& pythonPathStack)
  334. {
  335. // the order of the Python paths is the order the Python bootstrap scripts will execute
  336. auto settingsRegistry = AZ::SettingsRegistry::Get();
  337. if (!settingsRegistry)
  338. {
  339. return;
  340. }
  341. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  342. if (projectPath.empty())
  343. {
  344. return;
  345. }
  346. auto resolveScriptPath = [&pythonPathStack](AZStd::string_view path)
  347. {
  348. auto editorScriptsPath = AZ::IO::Path(path) / "Editor" / "Scripts";
  349. if (AZ::IO::SystemFile::Exists(editorScriptsPath.c_str()))
  350. {
  351. pythonPathStack.emplace_back(AZStd::move(editorScriptsPath.LexicallyNormal().Native()));
  352. }
  353. };
  354. // The discovery order will be:
  355. // 1 - engine-root/EngineAsets
  356. // 2 - gems
  357. // 3 - project
  358. // 4 - user(dev)
  359. // 1 - engine
  360. AZ::IO::FixedMaxPath engineRoot;
  361. if (settingsRegistry->Get(engineRoot.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); !engineRoot.empty())
  362. {
  363. resolveScriptPath((engineRoot / "Assets").Native());
  364. }
  365. // 2 - gems
  366. struct GetGemSourcePathsVisitor
  367. : AZ::SettingsRegistryInterface::Visitor
  368. {
  369. GetGemSourcePathsVisitor(AZ::SettingsRegistryInterface& settingsRegistry)
  370. : m_settingsRegistry(settingsRegistry)
  371. {}
  372. void Visit(AZStd::string_view path, AZStd::string_view, AZ::SettingsRegistryInterface::Type,
  373. AZStd::string_view value) override
  374. {
  375. AZStd::string_view jsonSourcePathPointer{ path };
  376. // Remove the array index from the path and check if the JSON path ends with "/SourcePaths"
  377. AZ::StringFunc::TokenizeLast(jsonSourcePathPointer, "/");
  378. if (jsonSourcePathPointer.ends_with("/SourcePaths"))
  379. {
  380. AZ::IO::Path newSourcePath = jsonSourcePathPointer;
  381. // Resolve any file aliases first - Do not use ResolvePath() as that assumes
  382. // any relative path is underneath the @assets@ alias
  383. if (auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); fileIoBase != nullptr)
  384. {
  385. AZ::IO::FixedMaxPath replacedAliasPath;
  386. if (fileIoBase->ReplaceAlias(replacedAliasPath, value))
  387. {
  388. newSourcePath = AZ::IO::PathView(replacedAliasPath);
  389. }
  390. }
  391. // The current assumption is that the gem source path is the relative to the engine root
  392. AZ::IO::Path engineRootPath;
  393. m_settingsRegistry.Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  394. newSourcePath = (engineRootPath / newSourcePath).LexicallyNormal();
  395. if (auto gemSourcePathIter = AZStd::find(m_gemSourcePaths.begin(), m_gemSourcePaths.end(), newSourcePath);
  396. gemSourcePathIter == m_gemSourcePaths.end())
  397. {
  398. m_gemSourcePaths.emplace_back(AZStd::move(newSourcePath));
  399. }
  400. }
  401. }
  402. AZStd::vector<AZ::IO::Path> m_gemSourcePaths;
  403. private:
  404. AZ::SettingsRegistryInterface& m_settingsRegistry;
  405. };
  406. GetGemSourcePathsVisitor visitor{ *settingsRegistry };
  407. constexpr auto gemListKey = AZ::SettingsRegistryInterface::FixedValueString(AZ::SettingsRegistryMergeUtils::OrganizationRootKey)
  408. + "/Gems";
  409. settingsRegistry->Visit(visitor, gemListKey);
  410. for (const AZ::IO::Path& gemSourcePath : visitor.m_gemSourcePaths)
  411. {
  412. resolveScriptPath(gemSourcePath.Native());
  413. }
  414. // 3 - project
  415. resolveScriptPath(AZStd::string_view{ projectPath });
  416. // 4 - user
  417. AZStd::string assetsType;
  418. AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, assetsType,
  419. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, AzFramework::AssetSystem::Assets);
  420. if (!assetsType.empty())
  421. {
  422. AZ::IO::FixedMaxPath userCachePath;
  423. if (settingsRegistry->Get(userCachePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_CacheRootFolder);
  424. !userCachePath.empty())
  425. {
  426. userCachePath /= "user";
  427. resolveScriptPath(userCachePath.Native());
  428. }
  429. }
  430. }
  431. void PythonSystemComponent::ExecuteBootstrapScripts(const PythonPathStack& pythonPathStack)
  432. {
  433. for(const auto& path : pythonPathStack)
  434. {
  435. AZStd::string bootstrapPath;
  436. AzFramework::StringFunc::Path::Join(path.c_str(), "bootstrap.py", bootstrapPath);
  437. if (AZ::IO::SystemFile::Exists(bootstrapPath.c_str()))
  438. {
  439. ExecuteByFilename(bootstrapPath);
  440. }
  441. }
  442. }
  443. bool PythonSystemComponent::StartPythonInterpreter(const PythonPathStack& pythonPathStack)
  444. {
  445. AZStd::unordered_set<AZStd::string> pyPackageSites(pythonPathStack.begin(), pythonPathStack.end());
  446. const char* engineRoot = nullptr;
  447. AzFramework::ApplicationRequests::Bus::BroadcastResult(engineRoot, &AzFramework::ApplicationRequests::GetEngineRoot);
  448. // set PYTHON_HOME
  449. AZStd::string pyBasePath = Platform::GetPythonHomePath(PY_PACKAGE, engineRoot);
  450. if (!AZ::IO::SystemFile::Exists(pyBasePath.c_str()))
  451. {
  452. AZ_Warning("python", false, "Python home path must exist! path:%s", pyBasePath.c_str());
  453. return false;
  454. }
  455. AZStd::wstring pyHomePath;
  456. AZStd::to_wstring(pyHomePath, pyBasePath);
  457. Py_SetPythonHome(pyHomePath.c_str());
  458. // display basic Python information
  459. AZ_TracePrintf("python", "Py_GetVersion=%s \n", Py_GetVersion());
  460. AZ_TracePrintf("python", "Py_GetPath=%ls \n", Py_GetPath());
  461. AZ_TracePrintf("python", "Py_GetExecPrefix=%ls \n", Py_GetExecPrefix());
  462. AZ_TracePrintf("python", "Py_GetProgramFullPath=%ls \n", Py_GetProgramFullPath());
  463. PyImport_AppendInittab("azlmbr_redirect", RedirectOutput::PyInit_RedirectOutput);
  464. try
  465. {
  466. // ignore system location for sites site-packages
  467. Py_IsolatedFlag = 1; // -I - Also sets Py_NoUserSiteDirectory. If removed PyNoUserSiteDirectory should be set.
  468. Py_IgnoreEnvironmentFlag = 1; // -E
  469. Py_InspectFlag = 1; // unhandled SystemExit will terminate the process unless Py_InspectFlag is set
  470. const bool initializeSignalHandlers = true;
  471. pybind11::initialize_interpreter(initializeSignalHandlers);
  472. // Add custom site packages after initializing the interpreter above. Calling Py_SetPath before initialization
  473. // 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
  474. if (pyPackageSites.size())
  475. {
  476. ExtendSysPath(pyPackageSites);
  477. }
  478. RedirectOutput::Intialize(PyImport_ImportModule("azlmbr_redirect"));
  479. // Acquire GIL before calling Python code
  480. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  481. pybind11::gil_scoped_acquire acquire;
  482. if (EditorPythonBindings::PythonSymbolEventBus::GetTotalNumOfEventHandlers() == 0)
  483. {
  484. m_symbolLogHelper = AZStd::make_shared<PythonSystemComponent::SymbolLogHelper>();
  485. }
  486. // print Python version using AZ logging
  487. const int verRet = PyRun_SimpleStringFlags("import sys \nprint (sys.version) \n", nullptr);
  488. AZ_Error("python", verRet == 0, "Error trying to fetch the version number in Python!");
  489. return verRet == 0 && !PyErr_Occurred();
  490. }
  491. catch ([[maybe_unused]] const std::exception& e)
  492. {
  493. AZ_Warning("python", false, "Py_Initialize() failed with %s!", e.what());
  494. return false;
  495. }
  496. }
  497. bool PythonSystemComponent::ExtendSysPath(const AZStd::unordered_set<AZStd::string>& extendPaths)
  498. {
  499. AZStd::unordered_set<AZStd::string> oldPathSet;
  500. auto SplitPath = [&oldPathSet](AZStd::string_view pathPart)
  501. {
  502. oldPathSet.emplace(pathPart);
  503. };
  504. AZ::StringFunc::TokenizeVisitor(Py_EncodeLocale(Py_GetPath(), nullptr), SplitPath, DELIM);
  505. bool appended{ false };
  506. AZStd::string pathAppend{ "import sys\n" };
  507. for (const auto& thisStr : extendPaths)
  508. {
  509. if (!oldPathSet.contains(thisStr))
  510. {
  511. pathAppend.append(AZStd::string::format("sys.path.append(r'%s')\n", thisStr.c_str()));
  512. appended = true;
  513. }
  514. }
  515. if (appended)
  516. {
  517. ExecuteByString(pathAppend.c_str(), false);
  518. return true;
  519. }
  520. return false;
  521. }
  522. bool PythonSystemComponent::StopPythonInterpreter()
  523. {
  524. if (Py_IsInitialized())
  525. {
  526. RedirectOutput::Shutdown();
  527. pybind11::finalize_interpreter();
  528. }
  529. else
  530. {
  531. AZ_Warning("python", false, "Did not finalize since Py_IsInitialized() was false.");
  532. }
  533. return !PyErr_Occurred();
  534. }
  535. void PythonSystemComponent::ExecuteByString(AZStd::string_view script, bool printResult)
  536. {
  537. if (!Py_IsInitialized())
  538. {
  539. AZ_Error("python", false, "Can not ExecuteByString() since the embeded Python VM is not ready.");
  540. return;
  541. }
  542. if (!script.empty())
  543. {
  544. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  545. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByString, script);
  546. // Acquire GIL before calling Python code
  547. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  548. pybind11::gil_scoped_acquire acquire;
  549. // Acquire scope for __main__ for executing our script
  550. pybind11::object scope = pybind11::module::import("__main__").attr("__dict__");
  551. bool shouldPrintValue = false;
  552. if (printResult)
  553. {
  554. // Attempt to compile our code to determine if it's an expression
  555. // i.e. a Python code object with only an rvalue
  556. // If it is, it can be evaled to produce a PyObject
  557. // If it's not, we can't evaluate it into a result and should fall back to exec
  558. shouldPrintValue = true;
  559. using namespace pybind11::literals;
  560. // codeop.compile_command is a thin wrapper around the Python compile builtin
  561. // We attempt to compile using symbol="eval" to see if the string is valid for eval
  562. // This is similar to what the Python REPL does internally
  563. pybind11::object codeop = pybind11::module::import("codeop");
  564. pybind11::object compileCommand = codeop.attr("compile_command");
  565. try
  566. {
  567. compileCommand(script.data(), "symbol"_a="eval");
  568. }
  569. catch (const pybind11::error_already_set&)
  570. {
  571. shouldPrintValue = false;
  572. }
  573. }
  574. try
  575. {
  576. if (shouldPrintValue)
  577. {
  578. // We're an expression, run and print the result
  579. pybind11::object result = pybind11::eval(script.data(), scope);
  580. pybind11::print(result);
  581. }
  582. else
  583. {
  584. // Just exec the code block
  585. pybind11::exec(script.data(), scope);
  586. }
  587. }
  588. catch (pybind11::error_already_set& pythonError)
  589. {
  590. // Release the exception stack and let Python print it to stderr
  591. pythonError.restore();
  592. PyErr_Print();
  593. }
  594. }
  595. }
  596. void PythonSystemComponent::ExecuteByFilename(AZStd::string_view filename)
  597. {
  598. AZStd::vector<AZStd::string_view> args;
  599. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  600. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilename, filename);
  601. ExecuteByFilenameWithArgs(filename, args);
  602. }
  603. bool PythonSystemComponent::ExecuteByFilenameAsTest(AZStd::string_view filename, AZStd::string_view testCase, const AZStd::vector<AZStd::string_view>& args)
  604. {
  605. AZ_TracePrintf("python", "Running automated test: %.*s (testcase %.*s)", AZ_STRING_ARG(filename), AZ_STRING_ARG(testCase))
  606. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  607. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilenameAsTest, filename, testCase, args);
  608. const Result evalResult = EvaluateFile(filename, args);
  609. return evalResult == Result::Okay;
  610. }
  611. void PythonSystemComponent::ExecuteByFilenameWithArgs(AZStd::string_view filename, const AZStd::vector<AZStd::string_view>& args)
  612. {
  613. AzToolsFramework::EditorPythonScriptNotificationsBus::Broadcast(
  614. &AzToolsFramework::EditorPythonScriptNotificationsBus::Events::OnStartExecuteByFilenameWithArgs, filename, args);
  615. EvaluateFile(filename, args);
  616. }
  617. PythonSystemComponent::Result PythonSystemComponent::EvaluateFile(AZStd::string_view filename, const AZStd::vector<AZStd::string_view>& args)
  618. {
  619. if (!Py_IsInitialized())
  620. {
  621. AZ_Error("python", false, "Can not evaluate file since the embedded Python VM is not ready.");
  622. return Result::Error_IsNotInitialized;
  623. }
  624. if (filename.empty())
  625. {
  626. AZ_Error("python", false, "Invalid empty filename detected.");
  627. return Result::Error_InvalidFilename;
  628. }
  629. // support the alias version of a script such as @devroot@/Editor/Scripts/select_story_anim_objects.py
  630. AZStd::string theFilename(filename);
  631. {
  632. char resolvedPath[AZ_MAX_PATH_LEN] = { 0 };
  633. AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(theFilename.c_str(), resolvedPath, AZ_MAX_PATH_LEN);
  634. theFilename = resolvedPath;
  635. }
  636. if (!AZ::IO::FileIOBase::GetInstance()->Exists(theFilename.c_str()))
  637. {
  638. AZ_Error("python", false, "Missing Python file named (%s)", theFilename.c_str());
  639. return Result::Error_MissingFile;
  640. }
  641. FILE* file = _Py_fopen(theFilename.data(), "rb");
  642. if (!file)
  643. {
  644. AZ_Error("python", false, "Missing Python file named (%s)", theFilename.c_str());
  645. return Result::Error_FileOpenValidation;
  646. }
  647. Result pythonScriptResult = Result::Okay;
  648. try
  649. {
  650. // Acquire GIL before calling Python code
  651. AZStd::lock_guard<decltype(m_lock)> lock(m_lock);
  652. pybind11::gil_scoped_acquire acquire;
  653. // Create standard "argc" / "argv" command-line parameters to pass in to the Python script via sys.argv.
  654. // argc = number of parameters. This will always be at least 1, since the first parameter is the script name.
  655. // argv = the list of parameters, in wchar format.
  656. // Our expectation is that the args passed into this function does *not* already contain the script name.
  657. int argc = aznumeric_cast<int>(args.size()) + 1;
  658. // Note: This allocates from PyMem to ensure that Python has access to the memory.
  659. wchar_t** argv = static_cast<wchar_t**>(PyMem_Malloc(argc * sizeof(wchar_t*)));
  660. // Python 3.x is expecting wchar* strings for the command-line args.
  661. argv[0] = Py_DecodeLocale(theFilename.c_str(), nullptr);
  662. for (int arg = 0; arg < args.size(); arg++)
  663. {
  664. AZStd::string argString(args[arg]);
  665. argv[arg + 1] = Py_DecodeLocale(argString.c_str(), nullptr);
  666. }
  667. // Tell Python the command-line args.
  668. // Note that this has a side effect of adding the script's path to the set of directories checked for "import" commands.
  669. const int updatePath = 1;
  670. PySys_SetArgvEx(argc, argv, updatePath);
  671. PyCompilerFlags flags;
  672. flags.cf_flags = 0;
  673. const int bAutoCloseFile = true;
  674. const int returnCode = PyRun_SimpleFileExFlags(file, theFilename.c_str(), bAutoCloseFile, &flags);
  675. if (returnCode != 0)
  676. {
  677. AZStd::string message = AZStd::string::format("Detected script failure in Python script(%s); return code %d!", theFilename.c_str(), returnCode);
  678. AZ_Warning("python", false, message.c_str());
  679. using namespace AzToolsFramework;
  680. EditorPythonConsoleNotificationBus::Broadcast(&EditorPythonConsoleNotificationBus::Events::OnExceptionMessage, message.c_str());
  681. pythonScriptResult = Result::Error_PythonException;
  682. }
  683. // Free any memory allocated for the command-line args.
  684. for (int arg = 0; arg < argc; arg++)
  685. {
  686. PyMem_RawFree(argv[arg]);
  687. }
  688. PyMem_Free(argv);
  689. }
  690. catch ([[maybe_unused]] const std::exception& e)
  691. {
  692. AZ_Error("python", false, "Detected an internal exception %s while running script (%s)!", e.what(), theFilename.c_str());
  693. return Result::Error_InternalException;
  694. }
  695. return pythonScriptResult;
  696. }
  697. } // namespace EditorPythonBindings