Skip to content

Commit 6f35219

Browse files
bpo-35931: Gracefully handle SyntaxError in pdb debug command (GH-11782)
Previously, `debug print(` would cause the interpreter to exit on a SyntaxError whereas `print(` would properly display the error and return to the pdb prompt. This patch fixes this by pre-compiling the code before passing it to `Pdb.run`. https://bugs.python.org/issue35931 (cherry picked from commit 4327705) Co-authored-by: Daniel Hahler <github@thequod.de>
1 parent 7a3cbcd commit 6f35219

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

Lib/pdb.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1093,10 +1093,16 @@ def do_debug(self, arg):
10931093
sys.settrace(None)
10941094
globals = self.curframe.f_globals
10951095
locals = self.curframe_locals
1096+
try:
1097+
code = compile(arg, "<string>", "exec")
1098+
except SyntaxError:
1099+
exc_info = sys.exc_info()[:2]
1100+
self.error(traceback.format_exception_only(*exc_info)[-1].strip())
1101+
return
10961102
p = Pdb(self.completekey, self.stdin, self.stdout)
10971103
p.prompt = "(%s) " % self.prompt.strip()
10981104
self.message("ENTERING RECURSIVE DEBUGGER")
1099-
sys.call_tracing(p.run, (arg, globals, locals))
1105+
sys.call_tracing(p.run, (code, globals, locals))
11001106
self.message("LEAVING RECURSIVE DEBUGGER")
11011107
sys.settrace(self.trace_dispatch)
11021108
self.lastcmd = p.lastcmd

Lib/test/test_pdb.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1482,6 +1482,14 @@ def test_relative_imports_on_plain_module(self):
14821482
stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands)
14831483
self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout)
14841484

1485+
def test_syntaxerror_in_command(self):
1486+
commands = "print(\ndebug print("
1487+
stdout, _ = self.run_pdb_script("", commands)
1488+
self.assertEqual(stdout.splitlines()[1:], [
1489+
'(Pdb) *** SyntaxError: unexpected EOF while parsing',
1490+
'(Pdb) *** SyntaxError: unexpected EOF while parsing',
1491+
'(Pdb) ',
1492+
])
14851493

14861494
def load_tests(*args):
14871495
from test import test_pdb
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The :mod:`pdb` ``debug`` command now gracefully handles syntax errors.

0 commit comments

Comments
 (0)