int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags) { PyObject *filename, *v; int ret, err; PyCompilerFlags local_flags; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) { PyErr_Print(); return -1; } if (flags == NULL) { flags = &local_flags; local_flags.cf_flags = 0; } v = _PySys_GetObjectId(&PyId_ps1); if (v == NULL) { _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> ")); Py_XDECREF(v); } v = _PySys_GetObjectId(&PyId_ps2); if (v == NULL) { _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... ")); Py_XDECREF(v); } err = -1; for (;;) { ret = PyRun_InteractiveOneObject(fp, filename, flags); _PY_DEBUG_PRINT_TOTAL_REFS(); if (ret == E_EOF) { err = 0; break; } /* if (ret == E_NOMEM) break; */ } Py_DECREF(filename); return err; }
int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags) { PyObject *filename, *v; int ret, err; PyCompilerFlags local_flags; int nomem_count = 0; #ifdef Py_REF_DEBUG int show_ref_count = _PyInterpreterState_Get()->core_config.show_ref_count; #endif filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) { PyErr_Print(); return -1; } if (flags == NULL) { flags = &local_flags; local_flags.cf_flags = 0; } v = _PySys_GetObjectId(&PyId_ps1); if (v == NULL) { _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> ")); Py_XDECREF(v); } v = _PySys_GetObjectId(&PyId_ps2); if (v == NULL) { _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... ")); Py_XDECREF(v); } err = 0; do { ret = PyRun_InteractiveOneObjectEx(fp, filename, flags); if (ret == -1 && PyErr_Occurred()) { /* Prevent an endless loop after multiple consecutive MemoryErrors * while still allowing an interactive command to fail with a * MemoryError. */ if (PyErr_ExceptionMatches(PyExc_MemoryError)) { if (++nomem_count > 16) { PyErr_Clear(); err = -1; break; } } else { nomem_count = 0; } PyErr_Print(); flush_io(); } else { nomem_count = 0; } #ifdef Py_REF_DEBUG if (show_ref_count) { _PyDebug_PrintTotalRefs(); } #endif } while (ret != E_EOF); Py_DECREF(filename); return err; }
void PyErr_PrintEx(int set_sys_last_vars) { PyObject *exception, *v, *tb, *hook; if (PyErr_ExceptionMatches(PyExc_SystemExit)) { handle_system_exit(); } PyErr_Fetch(&exception, &v, &tb); if (exception == NULL) return; PyErr_NormalizeException(&exception, &v, &tb); if (tb == NULL) { tb = Py_None; Py_INCREF(tb); } PyException_SetTraceback(v, tb); if (exception == NULL) return; /* Now we know v != NULL too */ if (set_sys_last_vars) { if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) { PyErr_Clear(); } if (_PySys_SetObjectId(&PyId_last_value, v) < 0) { PyErr_Clear(); } if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) { PyErr_Clear(); } } hook = _PySys_GetObjectId(&PyId_excepthook); if (hook) { PyObject* stack[3]; PyObject *result; stack[0] = exception; stack[1] = v; stack[2] = tb; result = _PyObject_FastCall(hook, stack, 3); if (result == NULL) { PyObject *exception2, *v2, *tb2; if (PyErr_ExceptionMatches(PyExc_SystemExit)) { handle_system_exit(); } PyErr_Fetch(&exception2, &v2, &tb2); PyErr_NormalizeException(&exception2, &v2, &tb2); /* It should not be possible for exception2 or v2 to be NULL. However PyErr_Display() can't tolerate NULLs, so just be safe. */ if (exception2 == NULL) { exception2 = Py_None; Py_INCREF(exception2); } if (v2 == NULL) { v2 = Py_None; Py_INCREF(v2); } fflush(stdout); PySys_WriteStderr("Error in sys.excepthook:\n"); PyErr_Display(exception2, v2, tb2); PySys_WriteStderr("\nOriginal exception was:\n"); PyErr_Display(exception, v, tb); Py_DECREF(exception2); Py_DECREF(v2); Py_XDECREF(tb2); } Py_XDECREF(result); } else { PySys_WriteStderr("sys.excepthook is missing\n"); PyErr_Display(exception, v, tb); } Py_XDECREF(exception); Py_XDECREF(v); Py_XDECREF(tb); }
PyThreadState * Py_NewInterpreter(void) { PyInterpreterState *interp; PyThreadState *tstate, *save_tstate; PyObject *bimod, *sysmod; if (!initialized) Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); #ifdef WITH_THREAD /* Issue #10915, #15751: The GIL API doesn't work with multiple interpreters: disable PyGILState_Check(). */ _PyGILState_check_enabled = 0; #endif interp = PyInterpreterState_New(); if (interp == NULL) return NULL; tstate = PyThreadState_New(interp); if (tstate == NULL) { PyInterpreterState_Delete(interp); return NULL; } save_tstate = PyThreadState_Swap(tstate); /* XXX The following is lax in error checking */ interp->modules = PyDict_New(); bimod = _PyImport_FindBuiltin("builtins"); if (bimod != NULL) { interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) goto handle_error; Py_INCREF(interp->builtins); } /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PyImport_FindBuiltin("sys"); if (bimod != NULL && sysmod != NULL) { PyObject *pstderr; interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) goto handle_error; Py_INCREF(interp->sysdict); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImportHooks_Init(); import_init(interp, sysmod); if (initfsencoding(interp) < 0) goto handle_error; if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); initmain(interp); if (!Py_NoSiteFlag) initsite(); } if (!PyErr_Occurred()) return tstate; handle_error: /* Oops, it didn't work. Undo it all. */ PyErr_PrintEx(0); PyThreadState_Clear(tstate); PyThreadState_Swap(save_tstate); PyThreadState_Delete(tstate); PyInterpreterState_Delete(interp); return NULL; }
void _Py_InitializeEx_Private(int install_sigs, int install_importlib) { PyInterpreterState *interp; PyThreadState *tstate; PyObject *bimod, *sysmod, *pstderr; char *p; extern void _Py_ReadyTypes(void); if (initialized) return; initialized = 1; _Py_Finalizing = NULL; #if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE) /* Set up the LC_CTYPE locale, so we can obtain the locale's charset without having to switch locales. */ setlocale(LC_CTYPE, ""); #endif if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') Py_DebugFlag = add_flag(Py_DebugFlag, p); if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') Py_VerboseFlag = add_flag(Py_VerboseFlag, p); if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); /* The variable is only tested for existence here; _PyRandom_Init will check its value further. */ if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0') Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p); _PyRandom_Init(); interp = PyInterpreterState_New(); if (interp == NULL) Py_FatalError("Py_Initialize: can't make first interpreter"); tstate = PyThreadState_New(interp); if (tstate == NULL) Py_FatalError("Py_Initialize: can't make first thread"); (void) PyThreadState_Swap(tstate); #ifdef WITH_THREAD /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because destroying the GIL might fail when it is being referenced from another running thread (see issue #9901). Instead we destroy the previously created GIL here, which ensures that we can call Py_Initialize / Py_FinalizeEx multiple times. */ _PyEval_FiniThreads(); /* Auto-thread-state API */ _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ _Py_ReadyTypes(); if (!_PyFrame_Init()) Py_FatalError("Py_Initialize: can't init frames"); if (!_PyLong_Init()) Py_FatalError("Py_Initialize: can't init longs"); if (!PyByteArray_Init()) Py_FatalError("Py_Initialize: can't init bytearray"); if (!_PyFloat_Init()) Py_FatalError("Py_Initialize: can't init float"); interp->modules = PyDict_New(); if (interp->modules == NULL) Py_FatalError("Py_Initialize: can't make modules dictionary"); /* Init Unicode implementation; relies on the codec registry */ if (_PyUnicode_Init() < 0) Py_FatalError("Py_Initialize: can't initialize unicode"); if (_PyStructSequence_Init() < 0) Py_FatalError("Py_Initialize: can't initialize structseq"); bimod = _PyBuiltin_Init(); if (bimod == NULL) Py_FatalError("Py_Initialize: can't initialize builtins modules"); _PyImport_FixupBuiltin(bimod, "builtins"); interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) Py_FatalError("Py_Initialize: can't initialize builtins dict"); Py_INCREF(interp->builtins); /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PySys_Init(); if (sysmod == NULL) Py_FatalError("Py_Initialize: can't initialize sys"); interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) Py_FatalError("Py_Initialize: can't initialize sys dict"); Py_INCREF(interp->sysdict); _PyImport_FixupBuiltin(sysmod, "sys"); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImport_Init(); _PyImportHooks_Init(); /* Initialize _warnings. */ _PyWarnings_Init(); if (!install_importlib) return; if (_PyTime_Init() < 0) Py_FatalError("Py_Initialize: can't initialize time"); import_init(interp, sysmod); /* initialize the faulthandler module */ if (_PyFaulthandler_Init()) Py_FatalError("Py_Initialize: can't initialize faulthandler"); if (initfsencoding(interp) < 0) Py_FatalError("Py_Initialize: unable to load the file system codec"); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ if (_PyTraceMalloc_Init() < 0) Py_FatalError("Py_Initialize: can't initialize tracemalloc"); initmain(interp); /* Module __main__ */ if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); /* Initialize warnings. */ if (PySys_HasWarnOptions()) { PyObject *warnings_module = PyImport_ImportModule("warnings"); if (warnings_module == NULL) { fprintf(stderr, "'import warnings' failed; traceback:\n"); PyErr_Print(); } Py_XDECREF(warnings_module); } if (!Py_NoSiteFlag) initsite(); /* Module site */ }
/* Initialize sys.stdin, stdout, stderr and builtins.open */ static int initstdio(void) { PyObject *iomod = NULL, *wrapper; PyObject *bimod = NULL; PyObject *m; PyObject *std = NULL; int status = 0, fd; PyObject * encoding_attr; char *pythonioencoding = NULL, *encoding, *errors; /* Hack to avoid a nasty recursion issue when Python is invoked in verbose mode: pre-import the Latin-1 and UTF-8 codecs */ if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) { goto error; } Py_DECREF(m); if (!(m = PyImport_ImportModule("encodings.latin_1"))) { goto error; } Py_DECREF(m); if (!(bimod = PyImport_ImportModule("builtins"))) { goto error; } if (!(iomod = PyImport_ImportModule("io"))) { goto error; } if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) { goto error; } /* Set builtins.open */ if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) { Py_DECREF(wrapper); goto error; } Py_DECREF(wrapper); encoding = _Py_StandardStreamEncoding; errors = _Py_StandardStreamErrors; if (!encoding || !errors) { pythonioencoding = Py_GETENV("PYTHONIOENCODING"); if (pythonioencoding) { char *err; pythonioencoding = _PyMem_Strdup(pythonioencoding); if (pythonioencoding == NULL) { PyErr_NoMemory(); goto error; } err = strchr(pythonioencoding, ':'); if (err) { *err = '\0'; err++; if (*err && !errors) { errors = err; } } if (*pythonioencoding && !encoding) { encoding = pythonioencoding; } } if (!errors && !(pythonioencoding && *pythonioencoding)) { /* When the LC_CTYPE locale is the POSIX locale ("C locale"), stdin and stdout use the surrogateescape error handler by default, instead of the strict error handler. */ char *loc = setlocale(LC_CTYPE, NULL); if (loc != NULL && strcmp(loc, "C") == 0) errors = "surrogateescape"; } } /* Set sys.stdin */ fd = fileno(stdin); /* Under some conditions stdin, stdout and stderr may not be connected * and fileno() may point to an invalid file descriptor. For example * GUI apps don't have valid standard streams by default. */ std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors); if (std == NULL) goto error; PySys_SetObject("__stdin__", std); _PySys_SetObjectId(&PyId_stdin, std); Py_DECREF(std); /* Set sys.stdout */ fd = fileno(stdout); std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors); if (std == NULL) goto error; PySys_SetObject("__stdout__", std); _PySys_SetObjectId(&PyId_stdout, std); Py_DECREF(std); #if 1 /* Disable this if you have trouble debugging bootstrap stuff */ /* Set sys.stderr, replaces the preliminary stderr */ fd = fileno(stderr); std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace"); if (std == NULL) goto error; /* Same as hack above, pre-import stderr's codec to avoid recursion when import.c tries to write to stderr in verbose mode. */ encoding_attr = PyObject_GetAttrString(std, "encoding"); if (encoding_attr != NULL) { const char * std_encoding; std_encoding = _PyUnicode_AsString(encoding_attr); if (std_encoding != NULL) { PyObject *codec_info = _PyCodec_Lookup(std_encoding); Py_XDECREF(codec_info); } Py_DECREF(encoding_attr); } PyErr_Clear(); /* Not a fatal error if codec isn't available */ if (PySys_SetObject("__stderr__", std) < 0) { Py_DECREF(std); goto error; } if (_PySys_SetObjectId(&PyId_stderr, std) < 0) { Py_DECREF(std); goto error; } Py_DECREF(std); #endif if (0) { error: status = -1; } /* We won't need them anymore. */ if (_Py_StandardStreamEncoding) { PyMem_RawFree(_Py_StandardStreamEncoding); _Py_StandardStreamEncoding = NULL; } if (_Py_StandardStreamErrors) { PyMem_RawFree(_Py_StandardStreamErrors); _Py_StandardStreamErrors = NULL; } PyMem_Free(pythonioencoding); Py_XDECREF(bimod); Py_XDECREF(iomod); return status; }