]> granicus.if.org Git - python/commitdiff
Issue #19771: Omit irrelevant message if package could not be initialized
authorMartin Panter <vadmium+py@gmail.com>
Sat, 12 Dec 2015 06:58:55 +0000 (06:58 +0000)
committerMartin Panter <vadmium+py@gmail.com>
Sat, 12 Dec 2015 06:58:55 +0000 (06:58 +0000)
Lib/runpy.py
Lib/test/test_cmd_line_script.py
Misc/NEWS

index c98af19af4e3a88803bda80087f1d4613221b402..af6205db49d494bd226b048144d59adab433c7b8 100644 (file)
@@ -132,6 +132,8 @@ def _get_module_details(mod_name, error=ImportError):
             pkg_main_name = mod_name + ".__main__"
             return _get_module_details(pkg_main_name, error)
         except error as e:
+            if mod_name not in sys.modules:
+                raise  # No module loaded; being a package is irrelevant
             raise error(("%s; %r is a package and cannot " +
                                "be directly executed") %(e, mod_name))
     loader = spec.loader
index 96711d693c6995a2bda98a892cf8674ee7229b01..afac62aac5fbe6f730c3dddfcc86963e90deb940 100644 (file)
@@ -442,6 +442,19 @@ class CmdLineTest(unittest.TestCase):
                 self.assertRegex(err, regex)
                 self.assertNotIn(b'Traceback', err)
 
+    def test_dash_m_bad_pyc(self):
+        with support.temp_dir() as script_dir, \
+                support.change_cwd(path=script_dir):
+            os.mkdir('test_pkg')
+            # Create invalid *.pyc as empty file
+            with open('test_pkg/__init__.pyc', 'wb'):
+                pass
+            err = self.check_dash_m_failure('test_pkg')
+            self.assertRegex(err, br'Error while finding spec.*'
+                br'ImportError.*bad magic number')
+            self.assertNotIn(b'is a package', err)
+            self.assertNotIn(b'Traceback', err)
+
     def test_dash_m_init_traceback(self):
         # These were wrapped in an ImportError and tracebacks were
         # suppressed; see Issue 14285
index 7e5f9d0e9ee782e146741c6b1642b13bca4fa7f5..4ce5b32ab011a59d0976d636367b7c17fa764e93 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -41,6 +41,10 @@ Library
   "runpy" module now lets exceptions from package initialization pass back to
   the caller, rather than raising ImportError.
 
+- Issue #19771: Also in runpy and the "-m" option, omit the irrelevant
+  message ". . . is a package and cannot be directly executed" if the package
+  could not even be initialized (e.g. due to a bad *.pyc file).
+
 - Issue #25177: Fixed problem with the mean of very small and very large
   numbers. As a side effect, statistics.mean and statistics.variance should
   be significantly faster.