Skip to content

Commit bebf775

Browse files
committed
gh-67224: Show source lines in tracebacks when using the -c option when running Python
1 parent 5345ac4 commit bebf775

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

Lib/linecache.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ def get_lines(name=name, *args, **kwargs):
182182
return True
183183
return False
184184

185+
185186
def _register_code(code, string, name):
186187
cache[code] = (
187188
len(string),

Lib/test/test_cmd_line_script.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,6 +683,16 @@ def test_syntaxerror_null_bytes_in_multiline_string(self):
683683
b'SyntaxError: source code cannot contain null bytes'
684684
]
685685
)
686+
687+
def test_source_lines_are_shown_when_running_source(self):
688+
_, _, stderr = assert_python_failure("-c", "1/0")
689+
expected_lines = [
690+
b'Traceback (most recent call last):',
691+
b' File "<stdin>", line 1, in <module>',
692+
b' 1/0',
693+
b' ~^~',
694+
b'ZeroDivisionError: division by zero']
695+
self.assertEqual(stderr.splitlines(), expected_lines)
686696

687697
def test_consistent_sys_path_for_direct_execution(self):
688698
# This test case ensures that the following all give the same

Python/pythonrun.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1147,8 +1147,15 @@ PyRun_StringFlags(const char *str, int start, PyObject *globals,
11471147
mod = _PyParser_ASTFromString(
11481148
str, &_Py_STR(anon_string), start, flags, arena);
11491149

1150-
if (mod != NULL)
1151-
ret = run_mod(mod, &_Py_STR(anon_string), globals, locals, flags, arena, NULL);
1150+
PyObject* source = PyUnicode_FromString(str);
1151+
if (!source) {
1152+
goto exit;
1153+
}
1154+
if (mod != NULL) {
1155+
ret = run_mod(mod, &_Py_STR(anon_string), globals, locals, flags, arena, source);
1156+
}
1157+
Py_DECREF(source);
1158+
exit:
11521159
_PyArena_Free(arena);
11531160
return ret;
11541161
}

0 commit comments

Comments
 (0)