gplugin/gplugin

Use new Python initialization method

17 months ago, Elliott Sales de Andrade
23e774c51300
Parents 2df958da5c90
Children 9c9f3a78a6f6
Use new Python initialization method

This uses the [initialization from Python 3.8](https://docs.python.org/3/c-api/init_config.html)
where available, which also fixes a deprecation warning on Python 3.11 for `PySys_SetArgvEx`.

Testing Done:
Compiled against Python 3.11; didn't test older versions.

Reviewed at https://reviews.imfreedom.org/r/2084/
--- a/python3/gplugin-python3-loader.c Sat Nov 05 01:43:09 2022 -0500
+++ b/python3/gplugin-python3-loader.c Wed Nov 23 22:47:04 2022 -0600
@@ -341,11 +341,33 @@
static gboolean
gplugin_python3_loader_init_python(void)
{
+#if PY_VERSION_HEX >= 0x03080000
+ PyConfig config;
+ PyStatus status;
+
+ PyConfig_InitIsolatedConfig(&config);
+ status = PyConfig_SetBytesString(&config, &config.program_name,
+ g_get_prgname());
+ if(PyStatus_Exception(status)) {
+ g_warning("Could not convert program name to wchar_t string.");
+ PyConfig_Clear(&config);
+ return FALSE;
+ }
+
+ status = Py_InitializeFromConfig(&config);
+ PyConfig_Clear(&config);
+
+ if(PyStatus_Exception(status)) {
+ g_warning("Could not initialize Python.");
+ return FALSE;
+ }
+#else /* PY_VERSION_HEX >= 0x03080000 */
wchar_t *argv[] = {NULL, NULL};
/* Initializes Python3 */
- if(!Py_IsInitialized())
+ if(!Py_IsInitialized()) {
Py_InitializeEx(FALSE);
+ }
argv[0] = Py_DecodeLocale(g_get_prgname(), NULL);
if(argv[0] == NULL) {
@@ -358,6 +380,7 @@
*/
PySys_SetArgvEx(1, argv, 0);
PyMem_RawFree(argv[0]);
+#endif /* PY_VERSION_HEX >= 0x03080000 */
/* initialize pygobject */
if(gplugin_python3_loader_init_pygobject()) {
--- a/python3/gplugin-python3-test-pygobject.c Sat Nov 05 01:43:09 2022 -0500
+++ b/python3/gplugin-python3-test-pygobject.c Wed Nov 23 22:47:04 2022 -0600
@@ -25,12 +25,33 @@
gint
main(gint argc, gchar *argv[])
{
+#if PY_VERSION_HEX >= 0x03080000
+ PyConfig config;
+ PyStatus status;
+
+ PyConfig_InitIsolatedConfig(&config);
+ status = PyConfig_SetBytesString(&config, &config.program_name, argv[0]);
+ if(PyStatus_Exception(status)) {
+ printf("failed to convert argv[0] to wchar_t string: %s\n", argv[0]);
+ PyConfig_Clear(&config);
+ return FALSE;
+ }
+
+ status = Py_InitializeFromConfig(&config);
+ PyConfig_Clear(&config);
+
+ if(PyStatus_Exception(status)) {
+ printf("Could not initialize Python.\n");
+ return FALSE;
+ }
+#else /* PY_VERSION_HEX >= 0x03080000 */
wchar_t *wargv[] = {NULL, NULL};
size_t len;
/* initialize python */
- if(!Py_IsInitialized())
+ if(!Py_IsInitialized()) {
Py_InitializeEx(FALSE);
+ }
/* setup wargv */
len = mbstowcs(NULL, argv[0], 0);
@@ -53,6 +74,7 @@
PySys_SetArgvEx(1, wargv, 0);
g_free(wargv[0]);
+#endif /* PY_VERSION_HEX >= 0x03080000 */
/* initialize pygobject */
pygobject_init(3, 0, 0);