cpython: 6b08429a3932 (original) (raw)
Mercurial > cpython
changeset 99391:6b08429a3932
Issue #5319: New Py_FinalizeEx() API to exit with status 120 on failure [#5319]
Martin Panter vadmium+py@gmail.com | |
---|---|
date | Mon, 30 Nov 2015 03🔞29 +0000 |
parents | c852c7d8d681 |
children | 962086677306 |
files | Doc/c-api/init.rst Doc/c-api/intro.rst Doc/c-api/sys.rst Doc/extending/embedding.rst Doc/includes/run-func.c Doc/library/sys.rst Doc/whatsnew/3.6.rst Include/pylifecycle.h Lib/test/test_cmd_line.py Misc/NEWS Misc/SpecialBuilds.txt Modules/main.c PC/bdist_wininst/install.c PC/python3.def Python/frozenmain.c Python/pylifecycle.c Python/pystate.c Tools/scripts/combinerefs.py |
diffstat | 18 files changed, 120 insertions(+), 58 deletions(-)[+] [-] Doc/c-api/init.rst 33 Doc/c-api/intro.rst 4 Doc/c-api/sys.rst 14 Doc/extending/embedding.rst 6 Doc/includes/run-func.c 4 Doc/library/sys.rst 7 Doc/whatsnew/3.6.rst 6 Include/pylifecycle.h 1 Lib/test/test_cmd_line.py 3 Misc/NEWS 3 Misc/SpecialBuilds.txt 8 Modules/main.c 8 PC/bdist_wininst/install.c 18 PC/python3.def 1 Python/frozenmain.c 4 Python/pylifecycle.c 52 Python/pystate.c 2 Tools/scripts/combinerefs.py 4 |
line wrap: on
line diff
--- a/Doc/c-api/init.rst +++ b/Doc/c-api/init.rst @@ -25,7 +25,7 @@ Initializing and finalizing the interpre triple: module; search; path single: PySys_SetArgv() single: PySys_SetArgvEx()
single: Py_Finalize()[](#l1.7)
single: Py_FinalizeEx()[](#l1.8)
Initialize the Python interpreter. In an application embedding Python, this
should be called before using any other Python/C API functions; with the
@@ -34,7 +34,7 @@ Initializing and finalizing the interpre
modules :mod:builtins
, :mod:__main__
and :mod:sys
. It also initializes
the module search path (sys.path
). It does not set sys.argv
; use
:c:func:PySys_SetArgvEx
for that. This is a no-op when called for a second time
- (without calling :c:func:
Py_FinalizeEx
first). There is no return value; it is a fatal error if the initialization fails.
@@ -48,19 +48,20 @@ Initializing and finalizing the interpre .. c:function:: int Py_IsInitialized() Return true (nonzero) when the Python interpreter has been initialized, false
- (zero) if not. After :c:func:
Py_FinalizeEx
is called, this returns false until :c:func:Py_Initialize
is called again.
-.. c:function:: void Py_Finalize()
+.. c:function:: int Py_FinalizeEx()
Undo all initializations made by :c:func:Py_Initialize
and subsequent use of
Python/C API functions, and destroy all sub-interpreters (see
:c:func:Py_NewInterpreter
below) that were created and not yet destroyed since
the last call to :c:func:Py_Initialize
. Ideally, this frees all memory
allocated by the Python interpreter. This is a no-op when called for a second
- time (without calling :c:func:
Py_Initialize
again first). There is no return - value; errors during finalization are ignored.
- time (without calling :c:func:
Py_Initialize
again first). Normally the - return value is 0. If there were errors during finalization
- (flushing buffered data), -1 is returned.
This function is provided for a number of reasons. An embedding application
might want to restart Python without having to restart the application itself.
@@ -79,7 +80,15 @@ Initializing and finalizing the interpre
freed. Some memory allocated by extension modules may not be freed. Some
extensions may not work properly if their initialization routine is called more
than once; this can happen if an application calls :c:func:
Py_Initialize
and
+ +.. c:function:: void Py_Finalize() +
Process-wide parameters
@@ -107,7 +116,7 @@ Process-wide parameters
Note that :data:sys.stderr
always uses the "backslashreplace" error
handler, regardless of this (or any other) setting.
- If :c:func:
Py_FinalizeEx
is called, this function will need to be called again in order to affect subsequent calls to :c:func:Py_Initialize
. Returns 0 if successful, a nonzero value on error (e.g. calling after the @@ -918,7 +927,7 @@ using the following functions: entry.) .. index::
single: Py_Finalize()[](#l1.76)
single: Py_FinalizeEx()[](#l1.77) single: Py_Initialize()[](#l1.78)
Extension modules are shared between (sub-)interpreters as follows: the first
@@ -928,7 +937,7 @@ using the following functions:
and filled with the contents of this copy; the extension's init
function is
not called. Note that this is different from what happens when an extension is
imported after the interpreter has been completely re-initialized by calling
- :c:func:
Py_FinalizeEx
and :c:func:Py_Initialize
; in that case, the extension'sinitmodule
function is called again. .. index:: single: close() (in module os) @@ -936,14 +945,14 @@ using the following functions:
.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
- .. index:: single: Py_FinalizeEx() Destroy the (sub-)interpreter represented by the given thread state. The given thread state must be the current thread state. See the discussion of thread states below. When the call returns, the current thread state is NULL. All thread states associated with this interpreter are destroyed. (The global interpreter lock must be held before calling this function and is still held
- when it returns.) :c:func:
Py_FinalizeEx
will destroy all sub-interpreters that haven't been explicitly destroyed at that point.
--- a/Doc/c-api/intro.rst
+++ b/Doc/c-api/intro.rst
@@ -578,9 +578,9 @@ Sometimes, it is desirable to "uninitial
application may want to start over (make another call to
:c:func:Py_Initialize
) or the application is simply done with its use of
Python and wants to free memory allocated by Python. This can be accomplished
-by calling :c:func:Py_Finalize
. The function :c:func:Py_IsInitialized
returns
+by calling :c:func:Py_FinalizeEx
. The function :c:func:Py_IsInitialized
returns
true if Python is currently in the initialized state. More information about
-these functions is given in a later chapter. Notice that :c:func:Py_Finalize
+these functions is given in a later chapter. Notice that :c:func:Py_FinalizeEx
does not free all memory allocated by the Python interpreter, e.g. memory
allocated by extension modules currently cannot be released.
--- a/Doc/c-api/sys.rst +++ b/Doc/c-api/sys.rst @@ -212,20 +212,24 @@ Process Control .. c:function:: void Py_Exit(int status) .. index::
single: Py_Finalize()[](#l3.7)
single: Py_FinalizeEx()[](#l3.8) single: exit()[](#l3.9)
- Exit the current process. This calls :c:func:
Py_Finalize
and then calls the - standard C library function
exit(status)
.
- Exit the current process. This calls :c:func:
Py_FinalizeEx
and then calls the - standard C library function
exit(status)
. If :c:func:Py_FinalizeEx
- indicates an error, the exit status is set to 120. +
- .. versionchanged:: 3.6
Errors from finalization no longer ignored.[](#l3.18)
.. c:function:: int Py_AtExit(void (*func) ()) .. index::
single: Py_Finalize()[](#l3.24)
single: Py_FinalizeEx()[](#l3.25) single: cleanup functions[](#l3.26)
- Register a cleanup function to be called by :c:func:
Py_FinalizeEx
. The cleanup function will be called with no arguments and should return no value. At most 32 cleanup functions can be registered. When the registration is successful, :c:func:Py_AtExit
returns0
; on failure, it returns-1
. The cleanup
--- a/Doc/extending/embedding.rst +++ b/Doc/extending/embedding.rst @@ -67,7 +67,9 @@ perform some operation on a file. :: Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print('Today is', ctime(time()))\n");
Py_Finalize();[](#l4.7)
if (Py_FinalizeEx() < 0) {[](#l4.8)
exit(120);[](#l4.9)
} @@ -76,7 +78,7 @@ The :c:func:}[](#l4.10) PyMem_RawFree(program);[](#l4.11) return 0;[](#l4.12)
Py_SetProgramName
function :c:func:Py_Initialize
to inform the interpreter about paths to Python run-time libraries. Next, the Python interpreter is initialized with :c:func:Py_Initialize
, followed by the execution of a hard-coded Python script -that prints the date and time. Afterwards, the :c:func:Py_Finalize
call shuts +that prints the date and time. Afterwards, the :c:func:Py_FinalizeEx
call shuts the interpreter down, followed by the end of the program. In a real program, you may want to get the Python script from another source, perhaps a text-editor routine, a file, or a database. Getting the Python code from a file can better
--- a/Doc/includes/run-func.c +++ b/Doc/includes/run-func.c @@ -63,6 +63,8 @@ main(int argc, char *argv[]) fprintf(stderr, "Failed to load "%s"\n", argv[1]); return 1; }
--- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -255,7 +255,7 @@ always available. (defaulting to zero), or another type of object. If it is an integer, zero is considered "successful termination" and any nonzero value is considered "abnormal termination" by shells and the like. Most systems require it to be
- in the range 0--127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of @@ -268,6 +268,11 @@ always available. the process when called from the main thread, and the exception is not intercepted.
- .. versionchanged:: 3.6
If an error occurs in the cleanup after the Python interpreter[](#l6.17)
has caught :exc:`SystemExit` (such as an error flushing buffered data[](#l6.18)
in the standard streams), the exit status is changed to 120.[](#l6.19)
--- a/Doc/whatsnew/3.6.rst
+++ b/Doc/whatsnew/3.6.rst
@@ -171,7 +171,8 @@ Optimizations
Build and C API Changes
=======================
-* None yet.
+* New :c:func:Py_FinalizeEx
API which indicates if flushing buffered data
- failed (:issue:
5319
). Deprecated @@ -247,4 +248,5 @@ Changes in the Python API Changes in the C API -------------------- -* None yet. +* :c:func:Py_Exit
(and the main interpreter) now override the exit status - with 120 if flushing buffered data failed. See :issue:
5319
.
--- a/Include/pylifecycle.h +++ b/Include/pylifecycle.h @@ -27,6 +27,7 @@ PyAPI_FUNC(void) Py_InitializeEx(int); PyAPI_FUNC(void) _Py_InitializeEx_Private(int, int); #endif PyAPI_FUNC(void) Py_Finalize(void); +PyAPI_FUNC(int) Py_FinalizeEx(void); PyAPI_FUNC(int) Py_IsInitialized(void); PyAPI_FUNC(PyThreadState *) Py_NewInterpreter(void); PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *);
--- a/Lib/test/test_cmd_line.py +++ b/Lib/test/test_cmd_line.py @@ -348,8 +348,9 @@ class CmdLineTest(unittest.TestCase): test.support.SuppressCrashReport().enter() sys.stdout.write('x') os.close(sys.stdout.fileno())"""
rc, out, err = assert_python_ok('-c', code)[](#l9.7)
rc, out, err = assert_python_failure('-c', code)[](#l9.8) self.assertEqual(b'', out)[](#l9.9)
self.assertEqual(120, rc)[](#l9.10) self.assertRegex(err.decode('ascii', 'ignore'),[](#l9.11) 'Exception ignored in.*\nOSError: .*')[](#l9.12)
--- a/Misc/NEWS +++ b/Misc/NEWS @@ -10,6 +10,9 @@ Release date: XXXX-XX-XX Core and Builtins ----------------- +- Issue #5319: New Py_FinalizeEx() API allowing Python to set an exit status
- Issue #25485: telnetlib.Telnet is now a context manager.
- Issue #24097: Fixed crash in object.reduce() if slot name is freed inside
--- a/Misc/SpecialBuilds.txt +++ b/Misc/SpecialBuilds.txt @@ -65,9 +65,9 @@ sys.getobjects(max[, type]) simply by virtue of being in the list. envvar PYTHONDUMPREFS
- If this envvar exists, Py_FinalizeEx() arranges to print a list of all still-live heap objects. This is printed twice, in different formats,
- before and after Py_FinalizeEx has cleaned up everything it can clean up. The first output block produces the repr() of each object so is more informative; however, a lot of stuff destined to die is still alive then. The second output block is much harder to work with (repr() can't be invoked @@ -144,7 +144,7 @@ Special gimmicks: envvar PYTHONMALLOCSTATS If this envvar exists, a report of pymalloc summary statistics is printed to
Changed in 2.5: The number of extra bytes allocated is 4*sizeof(size_t). Before it was 16 on all boxes, reflecting that Python couldn't make use of @@ -179,7 +179,7 @@ Each type object grows three new members */ int tp_maxalloc; -Allocation and deallocation code keeps these counts up to date. Py_Finalize() +Allocation and deallocation code keeps these counts up to date. Py_FinalizeEx() displays a summary of the info returned by sys.getcounts() (see below), along with assorted other special allocation counts (like the number of tuple allocations satisfied by a tuple free-list, the number of 1-character strings
--- a/Modules/main.c +++ b/Modules/main.c @@ -654,7 +654,7 @@ Py_Main(int argc, wchar_t *argv) Py_SetProgramName(wbuf); / Don't free wbuf, the argument to Py_SetProgramName
* must remain valid until the Py_Finalize is called.[](#l12.7)
* must remain valid until Py_FinalizeEx is called.[](#l12.8) */[](#l12.9) } else {[](#l12.10) Py_SetProgramName(argv[0]);[](#l12.11)
@@ -785,7 +785,11 @@ Py_Main(int argc, wchar_t **argv) sts = PyRun_AnyFileFlags(stdin, "", &cf) != 0; }
- if (Py_FinalizeEx() < 0) {
/* Value unlikely to be confused with a non-error exit status or[](#l12.18)
other special meaning */[](#l12.19)
sts = 120;[](#l12.20)
- }
#ifdef INSURE /* Insure++ is a memory analysis tool that aids in discovering
--- a/PC/bdist_wininst/install.c +++ b/PC/bdist_wininst/install.c @@ -709,7 +709,7 @@ static int prepare_script_environment(HI
- 1 if the Python-dll does not export the functions we need
- 2 if no install-script is specified in pathname
- 3 if the install-script file could not be opened
- the return value of PyRun_SimpleString() or Py_FinalizeEx() otherwise,
- which is 0 if everything is ok, -1 if an exception had occurred
- in the install-script. */ @@ -722,7 +722,7 @@ do_run_installscript(HINSTANCE hPython, DECLPROC(hPython, void, Py_Initialize, (void)); DECLPROC(hPython, int, PySys_SetArgv, (int, wchar_t **)); DECLPROC(hPython, int, PyRun_SimpleString, (char *));
- DECLPROC(hPython, int, Py_FinalizeEx, (void)); DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *));
@@ -730,7 +730,7 @@ do_run_installscript(HINSTANCE hPython, DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); if (!Py_Initialize || !PySys_SetArgv
|| !PyRun_SimpleString || !Py_Finalize)[](#l13.25)
|| !PyRun_SimpleString || !Py_FinalizeEx)[](#l13.26) return 1;[](#l13.27)
if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) @@ -777,7 +777,9 @@ do_run_installscript(HINSTANCE hPython, } } }
close(fh); return result; @@ -839,11 +841,11 @@ static int do_run_simple_script(HINSTANC int rc; DECLPROC(hPython, void, Py_Initialize, (void)); DECLPROC(hPython, void, Py_SetProgramName, (wchar_t *));
- DECLPROC(hPython, int, Py_FinalizeEx, (void)); DECLPROC(hPython, int, PyRun_SimpleString, (char *)); DECLPROC(hPython, void, PyErr_Print, (void));
- if (!Py_Initialize || !Py_SetProgramName || !Py_FinalizeEx || !PyRun_SimpleString || !PyErr_Print) return -1;
@@ -853,7 +855,9 @@ static int do_run_simple_script(HINSTANC rc = PyRun_SimpleString(script); if (rc) PyErr_Print();
--- a/PC/python3.def +++ b/PC/python3.def @@ -648,6 +648,7 @@ EXPORTS Py_FatalError=python36.Py_FatalError Py_FileSystemDefaultEncoding=python36.Py_FileSystemDefaultEncoding DATA Py_Finalize=python36.Py_Finalize
- Py_FinalizeEx=python36.Py_FinalizeEx Py_GetBuildInfo=python36.Py_GetBuildInfo Py_GetCompiler=python36.Py_GetCompiler Py_GetCopyright=python36.Py_GetCopyright
--- a/Python/frozenmain.c +++ b/Python/frozenmain.c @@ -99,7 +99,9 @@ Py_FrozenMain(int argc, char **argv) #ifdef MS_WINDOWS PyWinFreeze_ExeTerm(); #endif
error: PyMem_RawFree(argv_copy);
--- a/Python/pylifecycle.c +++ b/Python/pylifecycle.c @@ -154,8 +154,8 @@ Py_SetStandardStreamEncoding(const char return 0; } -/* Global initializations. Can be undone by Py_Finalize(). Don't
- call this twice without an intervening Py_Finalize() call. When +/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
- call this twice without an intervening Py_FinalizeEx() call. When initializations fail, a fatal error is issued and the function does not return. On return, the first thread and interpreter state have been created. @@ -327,11 +327,11 @@ void (void) PyThreadState_Swap(tstate);
- /* 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_Finalize multiple times. */[](#l16.23)
_PyEval_FiniThreads(); /* Auto-thread-state API */ @@ -477,28 +477,35 @@ file_is_closed(PyObject *fobj) return r > 0; } -static void +static int flush_std_files(void) { PyObject *fout = _PySys_GetObjectId(&PyId_stdout); PyObject *ferr = _PySys_GetObjectId(&PyId_stderr); PyObject *tmp;that we can call Py_Initialize / Py_FinalizeEx multiple times. */[](#l16.24)
- int status = 0;
if (fout != NULL && fout != Py_None && !file_is_closed(fout)) { tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
if (tmp == NULL)[](#l16.43)
if (tmp == NULL) {[](#l16.44) PyErr_WriteUnraisable(fout);[](#l16.45)
status = -1;[](#l16.46)
} if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) { tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");}[](#l16.47) else[](#l16.48) Py_DECREF(tmp);[](#l16.49)
if (tmp == NULL)[](#l16.54)
if (tmp == NULL) {[](#l16.55) PyErr_Clear();[](#l16.56)
status = -1;[](#l16.57)
} +}[](#l16.58) else[](#l16.59) Py_DECREF(tmp);[](#l16.60)
- return status;
} /* Undo the effect of Py_Initialize(). @@ -515,14 +522,15 @@ flush_std_files(void) */ -void -Py_Finalize(void) +int +Py_FinalizeEx(void) { PyInterpreterState *interp; PyThreadState *tstate;
return;[](#l16.81)
return status;[](#l16.82)
wait_for_thread_shutdown(); @@ -547,7 +555,9 @@ Py_Finalize(void) initialized = 0; /* Flush sys.stdout and sys.stderr */
/* Disable signal handling / PyOS_FiniInterrupts(); @@ -576,7 +586,9 @@ Py_Finalize(void) PyImport_Cleanup(); / Flush sys.stdout and sys.stderr (again, in case more was printed) */
/* Collect final garbage. This disposes of cycles created by * class definitions, for example. @@ -696,6 +708,13 @@ Py_Finalize(void) #endif call_ll_exitfuncs();
+} + +void +Py_Finalize(void) +{
} /* Create and initialize a new interpreter and thread, and return the @@ -803,7 +822,7 @@ handle_error: frames, and that it is its interpreter's only remaining thread. It is a fatal error to violate these constraints.
- (Py_FinalizeEx() doesn't have these constraints -- it zaps everything, regardless.) Locking: as above. @@ -1016,7 +1035,8 @@ create_stdio(PyObject* io, mode = "rb"; buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi", fd, mode, buffering,
Py_None, Py_None, Py_None, 0);[](#l16.135)
Py_None, Py_None, /* encoding, errors */[](#l16.136)
if (buf == NULL) goto error;Py_None, 0); /* newline, closefd */[](#l16.137)
@@ -1450,7 +1470,9 @@ call_ll_exitfuncs(void) void Py_Exit(int sts) {
--- a/Python/pystate.c +++ b/Python/pystate.c @@ -686,7 +686,7 @@ PyThreadState_IsCurrent(PyThreadState t } / Internal initialization/finalization functions called by
--- a/Tools/scripts/combinerefs.py +++ b/Tools/scripts/combinerefs.py @@ -6,7 +6,7 @@ combinerefs path A helper for analyzing PYTHONDUMPREFS output. When the PYTHONDUMPREFS envar is set in a debug build, at Python shutdown -time Py_Finalize() prints the list of all live objects twice: first it +time Py_FinalizeEx() prints the list of all live objects twice: first it prints the repr() of each object while the interpreter is still fully intact. After cleaning up everything it can, it prints all remaining live objects again, but the second time just prints their addresses, refcounts, and type @@ -41,7 +41,7 @@ CAUTION: If object is a container type, objects shown in the repr: the repr was captured from the first output block, and some of the containees may have been released since then. For example, it's common for the line showing the dict of interned strings to display -strings that no longer exist at the end of Py_Finalize; this can be recognized +strings that no longer exist at the end of Py_FinalizeEx; this can be recognized (albeit painfully) because such containees don't have a line of their own. The objects are listed in allocation order, with most-recently allocated