Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to search the code while in the Python debugger?

Simple question but I can't find the answer.

In the Perl debugger, one can search the code by using "/string" as in typing / followed with the string one is searching for.

Here's an example of a simple Perl debugging session where I'm looking for the word "init" to locate the subroutine initFromCfgFile. I find it at line 93 after using "/" twice:

% perl -d padmin.pl

Loading DB routines from perl5db.pl version 1.28
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(padmin.pl:18):   my $ACTION_STOP    = 'stop';
   DB<1> /init
59:     initFromCfgFile();

   DB<2> /
93:     sub initFromCfgFile {   


Is there a way to do the same with the Python debugger?

like image 809
Jerome Provensal Avatar asked Oct 24 '25 18:10

Jerome Provensal


1 Answers

You can subclass pdb.Pdb, which is a subclass of cmd.Cmd, with a do_find method to implement a find command (and a do_f attribute to implement a f command alias):

import pdb
import linecache

class fdb(pdb.Pdb):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.find = None

    def do_find(self, arg):
        if arg:
            self.find = arg
            self.last_lineno = 0
        elif not self.find:
            self.error('A search string must be specified.')
            return
        filename = self.curframe.f_code.co_filename
        for lineno, line in enumerate(linecache.getlines(filename, self.curframe.f_globals), 1):
            if lineno > self.last_lineno and self.find in line:
                self._print_lines([line], lineno)
                self.last_lineno = lineno
                break
        else:
            self.error(f'No {"more " if self.last_lineno else ""}matching line found.')
    do_f = do_find

fdb().set_trace()

Sample input and output:

--Return--
> test.py(26)<module>()->None
-> fdb().set_trace()
(Pdb) find
*** A search string must be specified.
(Pdb) find foobar
*** No matching line found.
(Pdb) find error
 14                 self.error('A search string must be specified.')
(Pdb) f
 23                 self.error(f'No {"more " if self.last_lineno else ""}matching line found.')
(Pdb) f
*** No more matching line found.
(Pdb) 

Demo: https://repl.it/@blhsing/PureHarmfulApplicationframework

like image 100
blhsing Avatar answered Oct 26 '25 06:10

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!