]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-127598: Improve ModuleNotFoundError when -S is passed (GH-136821)
authorMonadChains <monadchains@gmail.com>
Sun, 20 Jul 2025 13:33:58 +0000 (14:33 +0100)
committerGitHub <noreply@github.com>
Sun, 20 Jul 2025 13:33:58 +0000 (15:33 +0200)
Lib/test/test_traceback.py
Lib/traceback.py
Misc/NEWS.d/next/Core_and_Builtins/2025-07-19-17-08-09.gh-issue-127598.Mx8S-y.rst [new file with mode: 0644]

index 74b979d009664d9e4bdf2eb90df48a39d66f8180..11b7f419bddbe499188a4c06cffd6507e01833b9 100644 (file)
@@ -4748,7 +4748,26 @@ class MiscTest(unittest.TestCase):
         with self.assertRaises(TypeError):
             _suggestions._generate_suggestions(MyList(), "")
 
+    def test_no_site_package_flavour(self):
+        code = """import boo"""
+        _, _, stderr = assert_python_failure('-S', '-c', code)
 
+        self.assertIn(
+            (b"Site initialization is disabled, did you forget to "
+                b"add the site-packages directory to sys.path?"), stderr
+        )
+
+        code = """
+            import sys
+            sys.stdlib_module_names = sys.stdlib_module_names + ("boo",)
+            import boo
+        """
+        _, _, stderr = assert_python_failure('-S', '-c', code)
+
+        self.assertNotIn(
+            (b"Site initialization is disabled, did you forget to "
+                b"add the site-packages directory to sys.path?"), stderr
+        )
 
 
 class TestColorizedTraceback(unittest.TestCase):
index 31aa8695735f2b1515d8552d3a21c844f32665d7..f0dbb6352f776047b90bba69d334c68857ae8400 100644 (file)
@@ -1106,6 +1106,11 @@ class TracebackException:
             suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name)
             if suggestion:
                 self._str += f". Did you mean: '{suggestion}'?"
+        elif exc_type and issubclass(exc_type, ModuleNotFoundError) and \
+                sys.flags.no_site and \
+                getattr(exc_value, "name", None) not in sys.stdlib_module_names:
+            self._str += (". Site initialization is disabled, did you forget to "
+                + "add the site-packages directory to sys.path?")
         elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \
                 getattr(exc_value, "name", None) is not None:
             wrong_name = getattr(exc_value, "name", None)
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-07-19-17-08-09.gh-issue-127598.Mx8S-y.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-07-19-17-08-09.gh-issue-127598.Mx8S-y.rst
new file mode 100644 (file)
index 0000000..aff047b
--- /dev/null
@@ -0,0 +1,2 @@
+Improve :exc:`ModuleNotFoundError` by adding flavour text to the exception when the
+:option:`-S` option is passed. Patch by Andrea Mattei.