Skip to content

Commit

Permalink
pythongh-67224: Show source lines in tracebacks when using the -c opt…
Browse files Browse the repository at this point in the history
…ion when running Python

Signed-off-by: Pablo Galindo <pablogsal@gmail.com>
  • Loading branch information
pablogsal committed Oct 23, 2023
1 parent 9a9fba8 commit e0ebb00
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
8 changes: 5 additions & 3 deletions Lib/linecache.py
Expand Up @@ -5,10 +5,8 @@
that name.
"""

import functools
import sys
import os
import tokenize

__all__ = ["getline", "clearcache", "checkcache", "lazycache"]

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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),
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_cmd_line_script.py
Expand Up @@ -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 "<stdin>", line 1, in <module>',
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
Expand Down
@@ -0,0 +1,2 @@
Show source lines in tracebacks when using the ``-c`` option when running
Python. Patch by Pablo Galindo
11 changes: 9 additions & 2 deletions Python/pythonrun.c
Expand Up @@ -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;
}
Expand Down

0 comments on commit e0ebb00

Please sign in to comment.