summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rw-r--r--Lib/test/test_warnings/__init__.py17
-rw-r--r--Lib/warnings.py10
2 files changed, 25 insertions, 2 deletions
diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py
index eda755d..633b2ac 100644
--- a/Lib/test/test_warnings/__init__.py
+++ b/Lib/test/test_warnings/__init__.py
@@ -953,6 +953,23 @@ a=A()
# 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 --git a/Lib/warnings.py b/Lib/warnings.py
index 1d4fb20..cf9f5b2 100644
--- a/Lib/warnings.py
+++ b/Lib/warnings.py
@@ -21,9 +21,15 @@ def showwarning(message, category, filename, lineno, file=None, line=None):
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