How to programmatically exit pdb running in eval () or exec () without displaying output

In my python code, I have this line:

try:
    result = eval(command, self.globals, self.locals)
except SyntaxError:
    exec(command, self.globals, self.locals)

A variable commandcan be any string. Consequently, the python debugger pdbcan be started in eval/ execand still active when eval/ is returned exec. What I want to do is make sure that normal program execution resumes when I return from eval/ exec. To just give you an idea, this is about the behavior I want:

try:
    result = eval(command, self.globals, self.locals)
    try: self.globals['pdb'].run('continue')
    except: pass
except SyntaxError:
    exec(command, self.globals, self.locals)
    try: self.globals['pdb'].run('continue')
    except: pass

try , , . ... , , - , except.

, ?

< > :

IPython bpython, , , .

import pdb
pdb.set_trace()
next

, cpython, python. , , , python, - . , , python. >

+3
1

, eval/exec'ing , , , , .

, pdb , . . , , , - pdb . Pdb(). Resume_here() , . , , , , .

, foo(), , bar(), .

.

import sys
from pdb import Pdb

def trace_dispatch(self, frame, event, arg):
    if frame is self._resume_frame:
        self.set_continue()
        return
    return self._original_trace_dispatch(frame, event, arg)

def resume_here(self):
    Pdb._resume_frame = sys._getframe().f_back

# hotfix Pdb
Pdb._original_trace_dispatch = Pdb.trace_dispatch
Pdb.trace_dispatch = trace_dispatch
Pdb.resume_here = resume_here
Pdb._resume_frame = None

def foo():
    import pdb
    pdb.set_trace()
    print("tracing...")
    for i in range(3):
        print(i)

def bar():
    Pdb().resume_here()
    exec("foo();print('done')")
    print("returning")

bar()
+3

Source: https://habr.com/ru/post/1770105/


All Articles