1. 程式人生 > 其它 >遞迴除錯利器——adb

遞迴除錯利器——adb

m = 0
def fn(n):
    print('n = ', n)
    if n == 0: return 1
    x = 1 << (n + m)
    return x + fn(n - 1)

from cdb import Cdb
# 'x = fn()' is a statement. 'fn()' is both an expression and a statement.
# exec() returns None. eval(expr) returns the value of expr.
# run(cmd) debugs a statement executed via the exec() function.
# runeval(expr) debugs an expression executed via eval() function. cdb = Cdb(); cdb.ignore('fn'); cdb.run('fn(3)')
View Code
# The bdb module handles basic debugger functions, like setting breakpoints or managing execution via the debugger.
# The class bdb.Bdb() acts as a generic Python debugger base class. It takes care of the details of the trace facility;
# a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example. import bdb import linecache from cmdcolor import Color as C O = 'rgb' class Cdb(bdb.Bdb): def __init__(m, skip=None): bdb.Bdb.__init__(m, skip); m.framecnt = 0; m.ns = set(); m.ns.add('cdb'
); m.ns.add('Cdb') def ignore(m, name): m.ns.add(name) def pr_lines(m, f): def sl(m, obj): return [x for x in dir(obj) if not x.startswith('_')] # short list def sd(m, dic): return {k:v for (k,v) in dic.items() if not k.startswith('_') and not k in m.ns} # short dict fn = m.canonic(f.f_code.co_filename) for i in range(f.f_lineno - 1, f.f_lineno + 2): cur = i == f.f_lineno C('GB' if cur else 'g'),print(linecache.getline(fn, i), end=''), C(O) C('RGB', 'G'), print(' ', sd(m, f.f_globals), sd(m, f.f_locals), ' '), C(O) # Derived classes should override these methods to gain control over debugger operation. def user_call(m, frame, arg_list): 'Called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function.' m.framecnt += 1 def user_line(m, frame): 'Called from dispatch_line() when either stop_here() or break_here() yields True.' m.pr_lines(frame) def user_return(m, frame, ret_val): 'Called from dispatch_return() when stop_here() yields True.' if ret_val == None: return m.framecnt -= 1; C('R'); print(m.framecnt * ' ', 'Ret ', ret_val, sep=''); C(O) def user_exception(frame, exc_info): 'Called from dispatch_exception() when stop_here() yields True.' def do_clear(m, arg): 'Handle how a breakpoint must be removed when it is a temporary one.' 'This method MUST be implemented by derived classes.'
View Code
# termcolor outputs stuff like '\033[0m'. It doesn't work in Windows 10's cmd.

class Color:
    kernel32 = hStdOut = None
    
    def init():
        import ctypes
        Color.user32 = ctypes.CDLL('user32.dll'); Color.kernel32 = ctypes.CDLL('kernel32.dll')
        # https://docs.microsoft.com/en-us/windows/console/setconsoletextattribute
        # HANDLE WINAPI GetStdHandle(DWORD nStdHandle)
        # BOOL WINAPI SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttributes)
        # WINCON.H:
        #define FOREGROUND_BLUE      0x0001 // text color contains blue.
        #define FOREGROUND_GREEN     0x0002 // text color contains green.
        #define FOREGROUND_RED       0x0004 // text color contains red.
        #define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
        #define BACKGROUND_BLUE      0x0010 // background color contains blue.
        #define BACKGROUND_GREEN     0x0020 // background color contains green.
        #define BACKGROUND_RED       0x0040 // background color contains red.
        #define BACKGROUND_INTENSITY 0x0080 // background color is intensified.
        STD_OUTPUT_HANDLE = -11
        Color.hStdOut = Color.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    
    def __init__(m, fg_str_or_color, bg = ''):
        if isinstance(fg_str_or_color, int):
            import sys
            sys.stdout.flush()
            Color.kernel32.SetConsoleTextAttribute(Color.hStdOut, fg_str_or_color)
            return
        def f(s):
            t = { 'b':1, 'B':8+1, 'g':2, 'G':8+2, 'r':4, 'R':8+4 }
            d = 0
            for c in s: d |= t.get(c, 0)
            #print(s, hex(d))
            return d
        m.__init__(f(fg_str_or_color) | (f(bg) << 4))

    # 注意縮排和空行!縮排不對__str__成了__init__的內部函式,折騰了半天。    
    def __str__(m): return 'Color'
    
Color.init()

if __name__ == '__main__':
    Color('G'); print('Green ', end=''); Color('rgb'); print('gray')
    print(Color('RGB', 'G'), 'Hello', Color('rgb'), 'world')
    # Color Hello Color world
    # python先把引數求值完再去調print。
    # CMD的color命令也可以設顏色。color/?

# 如果有人想做個cmdcolor包,請把程式碼拿去自便。甚至可以擴充套件為WFP - Windows Fun Pack :-)
# 比如一個執行緒空白DialogBox,另一個幹事情。GetWindowDC()後就可以畫畫了。哪怕GetDC(NULL)
# 在螢幕上畫呢。pip install pywin32; D:\Python39\Lib\site-packages\PyWin32.chm
# 簡歷裡一句"開發過一個python wheel,在github上有n顆星"?I admit我愛幻想。
# win32console裡一堆函式,如SetConsoleTitle,就是沒有SetConsoleTextAttribute。
# 四子棋: https://www.cnblogs.com/funwithwords/p/15626636.html
# 畫線和實心橢圓…… GDI
View Code