Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

debugging - Is there a way to take a 'snapshot' of a python debug session at a breakpoint?

Is there a way to record the state (or take a 'snapshot') of all local/global variables (and call stack and other debug info) in a python debug session so that I can view it later?

I use VSCode with the Microsoft python extension to debug python. What I want to do is when I hit a breakpoint, like below, to have a way to save all the global/local variables so I can continue debugging and compare all the debug info between my saved 'snapshot' and the current state of the system. enter image description here

Does anyone know of a way to do this? Doesn't have to be VSCode compatible, but that would be nice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use globals() and locals() to obtain the current list of variables.

For example:

a = 10

def f():
    i = 0
    j = 3
    print(locals())
    print(globals())

f()

Means:

{'i': 0, 'j': 3}
{'a': 10, 'f': ..., other pre-defined variables}

As for saving it, perhaps using tools like pickle or dill to create a binary representation of the dictionary and treat the generated file as a snapshot?

For example, when we save the variables to the file snapshot.pkl:

import dill

a = 10

def f():
    i = 0
    j = 3
    with open('snapshot.pkl', 'wb') as fd:
        dill.dump({
            'locals': locals(),
            'globals': globals()
        }, fd)

f()

And then load it later in another file:

import dill


with open('snapshot.pkl', 'rb') as fd:
    state = dill.load(fd)
    print(state['locals'])

Output:

{'i': 0, 'j': 3}

For the call stack, I'm not sure if you want a nicely formatted call stack or simply having the information, but you can simply obtain it via the traceback module with the function traceback.format_stack (or traceback.print_stack).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...