Python Forum

Full Version: Basic experiment with the bdb module
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The standard module bdb deserves to be more widely known. I'm experimenting with it.
import bdb
import inspect
import os

class Mydb(bdb.Bdb):
    def head(self, frame):
        return f'{os.path.basename(frame.f_code.co_filename)}: {frame.f_lineno} :'

    def hprint(self, frame, *args, **kwargs):
        print(self.head(frame), *args, **kwargs)

    def user_call(self, frame, arg):
        # arg is None (see the doc of sys.settrace)
        L, n = inspect.getsourcelines(frame)
        self.hprint(frame, f'-> {L[frame.f_lineno - n].rstrip()} {frame.f_locals}')

    def user_line(self, frame):
        L, n = inspect.getsourcelines(frame)
        self.hprint(frame, L[frame.f_lineno - n], end='')

    def user_return(self, frame, value):
        L, n = inspect.getsourcelines(frame)
        self.hprint(frame, f'<- {frame.f_code.co_name}: {value}')

def eggs(x):
    return x + x

def spam(a, b):
    return f'{eggs(b)} {eggs(a)}'

def main():
    x = 2 + 2
    spam(7, 'ham')
    return x

if __name__ == '__main__':
    mydb = Mydb()
    mydb.runcall(main)
Output:
λ python paillasse/pseudopy/tentebdb.py tentebdb.py: 32 : x = 2 + 2 tentebdb.py: 33 : spam(7, 'ham') tentebdb.py: 28 : -> def spam(a, b): {'a': 7, 'b': 'ham'} tentebdb.py: 29 : return f'{eggs(b)} {eggs(a)}' tentebdb.py: 25 : -> def eggs(x): {'x': 'ham'} tentebdb.py: 26 : return x + x tentebdb.py: 26 : <- eggs: hamham tentebdb.py: 25 : -> def eggs(x): {'x': 7} tentebdb.py: 26 : return x + x tentebdb.py: 26 : <- eggs: 14 tentebdb.py: 29 : <- spam: hamham 14 tentebdb.py: 34 : return x tentebdb.py: 34 : <- main: 4
I seem to remember using this a long time ago.

Today I do all of my work using VSCode, and absolutely love the debugger that comes with the IDE, (which, although not sure, and too lazy to find out) comes built-in to the IDE).
Many other things I like about this IDE, and some I loathe (the way telemetry keeps sneaking in by way of new configuration options).
(Sep-09-2022, 10:23 PM)Larz60+ Wrote: [ -> ]and absolutely love the debugger that comes with the IDE
My goal here is to use the debugger to produce output in a special form instead of really debugging code. It is part of a small application where I use pseudo-python code to describe real-life procedures. I hope to specialize the bdb.Bdb class for this use case. I cannot use a IDE's debugger for this task, it is too rigid.