diff --git a/Lib/linecache.py b/Lib/linecache.py index c1c988d9df436c..329a14053458b7 100644 --- a/Lib/linecache.py +++ b/Lib/linecache.py @@ -5,10 +5,8 @@ that name. """ -import functools import sys import os -import tokenize __all__ = ["getline", "clearcache", "checkcache", "lazycache"] @@ -82,6 +80,8 @@ def updatecache(filename, module_globals=None): If something's wrong, print a message, discard the cache entry, and return an empty list.""" + import tokenize + if filename in cache: if len(cache[filename]) != 1: cache.pop(filename, None) @@ -176,11 +176,13 @@ def lazycache(filename, module_globals): get_source = getattr(loader, 'get_source', None) if name and get_source: - get_lines = functools.partial(get_source, name) + def get_lines(name=name, *args, **kwargs): + return get_source(name, *args, **kwargs) cache[filename] = (get_lines,) return True return False + def _register_code(code, string, name): cache[code] = ( len(string), diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py index 614c6b3c3b5299..83ef2d2cf65969 100644 --- a/Lib/test/test_cmd_line_script.py +++ b/Lib/test/test_cmd_line_script.py @@ -683,6 +683,16 @@ def test_syntaxerror_null_bytes_in_multiline_string(self): b'SyntaxError: source code cannot contain null bytes' ] ) + + def test_source_lines_are_shown_when_running_source(self): + _, _, stderr = assert_python_failure("-c", "1/0") + expected_lines = [ + b'Traceback (most recent call last):', + b' File "", line 1, in ', + b' 1/0', + b' ~^~', + b'ZeroDivisionError: division by zero'] + self.assertEqual(stderr.splitlines(), expected_lines) def test_consistent_sys_path_for_direct_execution(self): # This test case ensures that the following all give the same diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-10-23-15-44-47.gh-issue-67224.S4D6CR.rst b/Misc/NEWS.d/next/Core and Builtins/2023-10-23-15-44-47.gh-issue-67224.S4D6CR.rst new file mode 100644 index 00000000000000..b0474f38cff6f6 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-10-23-15-44-47.gh-issue-67224.S4D6CR.rst @@ -0,0 +1,2 @@ +Show source lines in tracebacks when using the ``-c`` option when running +Python. Patch by Pablo Galindo diff --git a/Python/pythonrun.c b/Python/pythonrun.c index b915c063d0b456..2382ec6a14fe00 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -1147,8 +1147,15 @@ PyRun_StringFlags(const char *str, int start, PyObject *globals, mod = _PyParser_ASTFromString( str, &_Py_STR(anon_string), start, flags, arena); - if (mod != NULL) - ret = run_mod(mod, &_Py_STR(anon_string), globals, locals, flags, arena, NULL); + PyObject* source = PyUnicode_FromString(str); + if (!source) { + goto exit; + } + if (mod != NULL) { + ret = run_mod(mod, &_Py_STR(anon_string), globals, locals, flags, arena, source); + } + Py_DECREF(source); +exit: _PyArena_Free(arena); return ret; }