changeset: 100725:1de90a7065ba branch: 3.5 user: Victor Stinner date: Fri Mar 25 00:30:32 2016 +0100 files: Lib/test/test_warnings/__init__.py Lib/warnings.py Misc/NEWS description: warnings.formatwarning(): catch exceptions Issue #21925: warnings.formatwarning() now catches exceptions on linecache.getline(...) to be able to log ResourceWarning emitted late during the Python shutdown process. diff -r 34e607643fd1 -r 1de90a7065ba Lib/test/test_warnings/__init__.py --- a/Lib/test/test_warnings/__init__.py Fri Mar 25 00:28:56 2016 +0100 +++ b/Lib/test/test_warnings/__init__.py Fri Mar 25 00:30:32 2016 +0100 @@ -953,6 +953,23 @@ # of the script self.assertEqual(err, b'__main__:7: UserWarning: test') + def test_late_resource_warning(self): + # Issue #21925: Emitting a ResourceWarning late during the Python + # shutdown must be logged. + + expected = b"sys:1: ResourceWarning: unclosed file " + + # don't import the warnings module + # (_warnings will try to import it) + code = "f = open(%a)" % __file__ + rc, out, err = assert_python_ok("-c", code) + self.assertTrue(err.startswith(expected), ascii(err)) + + # import the warnings module + code = "import warnings; f = open(%a)" % __file__ + rc, out, err = assert_python_ok("-c", code) + self.assertTrue(err.startswith(expected), ascii(err)) + def setUpModule(): py_warnings.onceregistry.clear() diff -r 34e607643fd1 -r 1de90a7065ba Lib/warnings.py --- a/Lib/warnings.py Fri Mar 25 00:28:56 2016 +0100 +++ b/Lib/warnings.py Fri Mar 25 00:30:32 2016 +0100 @@ -21,9 +21,15 @@ def formatwarning(message, category, filename, lineno, line=None): """Function to format a warning the standard way.""" - import linecache s = "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) - line = linecache.getline(filename, lineno) if line is None else line + if line is None: + try: + import linecache + line = linecache.getline(filename, lineno) + except Exception: + # When a warning is logged during Python shutdown, linecache + # and the improt machinery don't work anymore + line = None if line: line = line.strip() s += " %s\n" % line diff -r 34e607643fd1 -r 1de90a7065ba Misc/NEWS --- a/Misc/NEWS Fri Mar 25 00:28:56 2016 +0100 +++ b/Misc/NEWS Fri Mar 25 00:30:32 2016 +0100 @@ -94,6 +94,10 @@ Library ------- +- Issue #21925: :func:`warnings.formatwarning` now catches exceptions on + ``linecache.getline(...)`` to be able to log :exc:`ResourceWarning` emitted + late during the Python shutdown process. + - Issue #24266: Ctrl+C during Readline history search now cancels the search mode when compiled with Readline 7.