8000 bpo-40108: Improve the error message in runpy when importing a module… · python/cpython@ef67512 · GitHub
[go: up one dir, main page]

Skip to content

Commit ef67512

Browse files
authored
bpo-40108: Improve the error message in runpy when importing a module that includes the extension (GH-19239)
1 parent c49016e commit ef67512

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

Lib/runpy.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,9 @@ def _get_module_details(mod_name, error=ImportError):
133133
# importlib, where the latter raises other errors for cases where
134134
# pkgutil previously raised ImportError
135135
msg = "Error while finding module specification for {!r} ({}: {})"
136+
if mod_name.endswith(".py"):
137+
msg += (f". Try using '{mod_name[:-3]}' instead of "
138+
f"'{mod_name}' as the module name.")
136139
raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex
137140
if spec is None:
138141
raise error("No module named %s" % mod_name)

Lib/test/test_cmd_line_script.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,16 @@ def test_dash_m_bad_pyc(self):
499499
self.assertNotIn(b'is a package', err)
500500
self.assertNotIn(b'Traceback', err)
501501

502+
def test_hint_when_triying_to_import_a_py_file(self):
503+
with support.temp_dir() as script_dir, \
504+
support.change_cwd(path=script_dir):
505+
# Create invalid *.pyc as empty file
506+
with open('asyncio.py', 'wb'):
507+
pass
508+
err = self.check_dash_m_failure('asyncio.py')
509+
self.assertIn(b"Try using 'asyncio' instead "
510+
b"of 'asyncio.py' as the module name", err)
511+
502512
def test_dash_m_init_traceback(self):
503513
# These were wrapped in an ImportError and tracebacks were
504514
# suppressed; see Issue 14285
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Improve the error message when triying to import a module using :mod:`runpy`
2+
and incorrently use the ".py" extension at the end of the module name. Patch
3+
by Pablo Galindo.

0 commit comments

Comments
 (0)
0