Skip to content

Commit 035681b

Browse files
pablogsalaisk
authored andcommitted
pythongh-67224: Show source lines in tracebacks when using the -c option when running Python (python#111200)
1 parent 0e8e5ec commit 035681b

File tree

13 files changed

+104
-36
lines changed

13 files changed

+104
-36
lines changed

Include/internal/pycore_pylifecycle.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ extern int _Py_LegacyLocaleDetected(int warn);
114114
// Export for 'readline' shared extension
115115
PyAPI_FUNC(char*) _Py_SetLocaleFromEnv(int category);
116116

117+
// Export for special main.c string compiling with source tracebacks
118+
int _PyRun_SimpleStringFlagsWithName(const char *command, const char* name, PyCompilerFlags *flags);
119+
117120
#ifdef __cplusplus
118121
}
119122
#endif

Lib/linecache.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,8 @@
55
that name.
66
"""
77

8-
import functools
98
import sys
109
import os
11-
import tokenize
1210

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

@@ -82,6 +80,8 @@ def updatecache(filename, module_globals=None):
8280
If something's wrong, print a message, discard the cache entry,
8381
and return an empty list."""
8482

83+
import tokenize
84+
8585
if filename in cache:
8686
if len(cache[filename]) != 1:
8787
cache.pop(filename, None)
@@ -176,11 +176,13 @@ def lazycache(filename, module_globals):
176176
get_source = getattr(loader, 'get_source', None)
177177

178178
if name and get_source:
179-
get_lines = functools.partial(get_source, name)
179+
def get_lines(name=name, *args, **kwargs):
180+
return get_source(name, *args, **kwargs)
180181
cache[filename] = (get_lines,)
181182
return True
182183
return False
183184

185+
184186
def _register_code(code, string, name):
185187
cache[code] = (
186188
len(string),

Lib/test/test_cmd_line_script.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,6 +684,16 @@ def test_syntaxerror_null_bytes_in_multiline_string(self):
684684
]
685685
)
686686

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 "<string>", line 1, in <module>',
692+
b' 1/0',
693+
b' ~^~',
694+
b'ZeroDivisionError: division by zero']
695+
self.assertEqual(stderr.splitlines(), expected_lines)
696+
687697
def test_syntaxerror_does_not_crash(self):
688698
script = "nonlocal x\n"
689699
with os_helper.temp_dir() as script_dir:

Lib/test/test_io.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4396,11 +4396,11 @@ def test_check_encoding_warning(self):
43964396
''')
43974397
proc = assert_python_ok('-X', 'warn_default_encoding', '-c', code)
43984398
warnings = proc.err.splitlines()
4399-
self.assertEqual(len(warnings), 2)
4399+
self.assertEqual(len(warnings), 4)
44004400
self.assertTrue(
44014401
warnings[0].startswith(b"<string>:5: EncodingWarning: "))
44024402
self.assertTrue(
4403-
warnings[1].startswith(b"<string>:8: EncodingWarning: "))
4403+
warnings[2].startswith(b"<string>:8: EncodingWarning: "))
44044404

44054405
def test_text_encoding(self):
44064406
# PEP 597, bpo-47000. io.text_encoding() returns "locale" or "utf-8"

Lib/test/test_repl.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ def bar(x):
184184
p.stdin.write(user_input)
185185
user_input2 = dedent("""
186186
import linecache
187-
print(linecache.cache['<python-input-1>'])
187+
print(linecache.cache['<stdin>-1'])
188188
""")
189189
p.stdin.write(user_input2)
190190
output = kill_python(p)

Lib/test/test_subprocess.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1769,9 +1769,9 @@ def test_encoding_warning(self):
17691769
cp = subprocess.run([sys.executable, "-Xwarn_default_encoding", "-c", code],
17701770
capture_output=True)
17711771
lines = cp.stderr.splitlines()
1772-
self.assertEqual(len(lines), 2, lines)
1772+
self.assertEqual(len(lines), 4, lines)
17731773
self.assertTrue(lines[0].startswith(b"<string>:2: EncodingWarning: "))
1774-
self.assertTrue(lines[1].startswith(b"<string>:3: EncodingWarning: "))
1774+
self.assertTrue(lines[2].startswith(b"<string>:3: EncodingWarning: "))
17751775

17761776

17771777
def _get_test_grp_name():

Lib/test/test_sys.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1114,14 +1114,18 @@ def check(tracebacklimit, expected):
11141114
traceback = [
11151115
b'Traceback (most recent call last):',
11161116
b' File "<string>", line 8, in <module>',
1117+
b' f2()',
11171118
b' File "<string>", line 6, in f2',
1119+
b' f1()',
11181120
b' File "<string>", line 4, in f1',
1121+
b' 1 / 0',
1122+
b' ~~^~~',
11191123
b'ZeroDivisionError: division by zero'
11201124
]
11211125
check(10, traceback)
11221126
check(3, traceback)
1123-
check(2, traceback[:1] + traceback[2:])
1124-
check(1, traceback[:1] + traceback[3:])
1127+
check(2, traceback[:1] + traceback[3:])
1128+
check(1, traceback[:1] + traceback[5:])
11251129
check(0, [traceback[-1]])
11261130
check(-1, [traceback[-1]])
11271131
check(1<<1000, traceback)

Lib/test/test_traceback.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,8 @@ def __del__(self):
313313
rc, stdout, stderr = assert_python_ok('-c', code)
314314
expected = [b'Traceback (most recent call last):',
315315
b' File "<string>", line 8, in __init__',
316+
b' x = 1 / 0',
317+
b' ^^^^^',
316318
b'ZeroDivisionError: division by zero']
317319
self.assertEqual(stderr.splitlines(), expected)
318320

Lib/test/test_warnings/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1233,6 +1233,10 @@ def test_conflicting_envvar_and_command_line(self):
12331233
self.assertEqual(stderr.splitlines(),
12341234
[b"Traceback (most recent call last):",
12351235
b" File \"<string>\", line 1, in <module>",
1236+
b' import sys, warnings; sys.stdout.write(str(sys.warnoptions)); warnings.w'
1237+
b"arn('Message', DeprecationWarning)",
1238+
b' ^^^^^^^^^^'
1239+
b'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^',
12361240
b"DeprecationWarning: Message"])
12371241

12381242
def test_default_filter_configuration(self):

Lib/traceback.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -476,12 +476,11 @@ def format_frame_summary(self, frame_summary):
476476
gets called for every frame to be printed in the stack summary.
477477
"""
478478
row = []
479-
if frame_summary.filename.startswith("<python-input"):
480-
row.append(' File "<stdin>", line {}, in {}\n'.format(
481-
frame_summary.lineno, frame_summary.name))
482-
else:
483-
row.append(' File "{}", line {}, in {}\n'.format(
484-
frame_summary.filename, frame_summary.lineno, frame_summary.name))
479+
filename = frame_summary.filename
480+
if frame_summary.filename.startswith("<stdin>-"):
481+
filename = "<stdin>"
482+
row.append(' File "{}", line {}, in {}\n'.format(
483+
filename, frame_summary.lineno, frame_summary.name))
485484
if frame_summary.line:
486485
stripped_line = frame_summary.line.strip()
487486
row.append(' {}\n'.format(stripped_line))

0 commit comments

Comments
 (0)