Commit 4726e40e authored by Victor Stinner's avatar Victor Stinner

Rewrite RunMainFromImporter()

 * fix argv0 reference counter if PyList_SetItem() fails
 * don't use complex if conditions, but a simple indentation and "goto error"
 * simplify error handling (remove Py_XDECREF(importer) from the error label)
 * don't set sys_path to NULL (it's useless, sys_path is a borrowed reference
   and sys_path is not a static variable)
 * try to write only one instruction per line for better readability
parent c08ec9fd
...@@ -228,35 +228,45 @@ static int RunModule(wchar_t *modname, int set_argv0) ...@@ -228,35 +228,45 @@ static int RunModule(wchar_t *modname, int set_argv0)
return 0; return 0;
} }
static int RunMainFromImporter(wchar_t *filename) static int
RunMainFromImporter(wchar_t *filename)
{ {
PyObject *argv0 = NULL, *importer = NULL; PyObject *argv0 = NULL, *importer, *sys_path;
int sts;
if ((argv0 = PyUnicode_FromWideChar(filename,wcslen(filename))) && argv0 = PyUnicode_FromWideChar(filename, wcslen(filename));
(importer = PyImport_GetImporter(argv0)) && if (argv0 == NULL)
(importer->ob_type != &PyNullImporter_Type)) goto error;
{
/* argv0 is usable as an import source, so importer = PyImport_GetImporter(argv0);
put it in sys.path[0] and import __main__ */ if (importer == NULL)
PyObject *sys_path = NULL; goto error;
if ((sys_path = PySys_GetObject("path")) &&
!PyList_SetItem(sys_path, 0, argv0)) if (importer->ob_type == &PyNullImporter_Type) {
{ Py_DECREF(argv0);
Py_INCREF(argv0); Py_DECREF(importer);
Py_DECREF(importer);
sys_path = NULL;
return RunModule(L"__main__", 0) != 0;
}
}
Py_XDECREF(argv0);
Py_XDECREF(importer);
if (PyErr_Occurred()) {
PyErr_Print();
return 1;
}
else {
return -1; return -1;
} }
Py_DECREF(importer);
/* argv0 is usable as an import source, so put it in sys.path[0]
and import __main__ */
sys_path = PySys_GetObject("path");
if (sys_path == NULL)
goto error;
if (PyList_SetItem(sys_path, 0, argv0)) {
argv0 = NULL;
goto error;
}
Py_INCREF(argv0);
sts = RunModule(L"__main__", 0);
return sts != 0;
error:
Py_XDECREF(argv0);
PyErr_Print();
return 1;
} }
static int static int
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment