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
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…