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

做~自己de王妃 提交于 2019-12-21 20:49:57

问题


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]

回答1:


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.



来源:https://stackoverflow.com/questions/1114080/is-it-possible-to-pass-a-variable-out-of-a-pdb-session-into-the-original-interac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!