Search code examples
pythonpdb

How to export a variable from PDB?


Imagine the following scenario: a script is started from the IPython shell and at a break point the python debugger is called. Using the PDB commands one can analyze the code and variables at this point. But often it turns out that the values of the variables call for a deeper research.

Is it possible to export the value of a variable to the IPython shell?

My specific use case: I struggle with a quite huge numpy array which does not seem to have the correct values. I know that I can run any python commands from the python debugger, but it would be helpful to save the values of the variable at different break points and to use all of them at IPython shell. I am imaging something like

ipdb> global var1; var1 = var
ipdb> continue
...
ipdb> global var2; var2 = var
ipdb> continue
... 
In [2]: abs(var1 - var2) # do some interesting calculations with IPython

Solution

  • You can use globals():

    ipdb>__name__
    'my_module'
    ipdb> get_var = 'a value'
    ipdb> globals()['myvar'] = get_var
    ipdb> q
    In [11]: my_module.myvar
    Out[11]: 'a value'
    

    This assumes the break point is set in my_module.py, so we are editing the globals of the module my_module.