Is it possible to pass a variable out of a pdb session into the original interactive session?

StackOverflow https://stackoverflow.com/questions/1114080

  •  12-09-2019
  •  | 
  •  

Question

I am using pdb to examine a script having called run -d in an ipython session. It would be useful to be able to plot some of the variables but I need them in the main ipython environment in order to do that.

So what I am looking for is some way to make a variable available back in the main interactive session after I quit pdb. If you set a variable in the topmost frame it does seem to be there in the ipython session, but this doesn't work for any frames further down.

Something like export in the following:

ipdb> myvar = [1,2,3]
ipdb> p myvar
[1, 2, 3]
ipdb> export myvar
ipdb> q

In [66]: myvar
Out[66]: [1, 2, 3]
Was it helpful?

Solution

Per ipython's docs, and also a run? command from the ipython prompt,

after execution, the IPython interactive namespace gets updated with all variables defined in the program (except for __name__ and sys.argv)

By "defined in the program" (a slightly sloppy use of terms), it doesn't mean "anywhere within any nested functions found there" -- it means "in the globals() of the script/module you're running. If you're within any kind of nesting, globals()['myvar'] = [1,2,3] should still work fine, just like your hoped-for export would if it existed.

Edit: If you're in a different module, you need to set the name in the globals of your original one -- after an import sys if needed, sys.modules["originalmodule"].myvar = [1, 2, 3] will do what you desire.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top