17

I've tried to look everywhere for a simple way to regain MATLAB-like functionality: when I run a script, I want ipython to maintain the namespace of my functions.

I have a main function, and then I have a function sim_loop() that has the code I'm trying to debug. sim_loop() has a large array that I want to be able to display after my script runs. I can't get that functionality to work (I assume it's "interactive namespace").

I've got pdb to work, but if I exit out of pdb and want to check a variable I have to run it all again (not to mention, there's no autocomplete and other functionality). I've embedded an IPython shell into my script, but, again, that doesn't address my problem because I want to seamlessly execute a script over and over again and constantly check a variable inside my second function (not main()).

To clarify I want to be able to access the scope of a subroutine of my script after the script has run from within ipython.

ie: I start ipython. I then type "run script.py". It runs and works perfectly fine. I want to be able to then inspect the variable "dummy" that was within the scope: main->sim_loop->dummy

I want to be able to inspect it and then run my script again with "run script.py" and then check "dummy" again ad nauseum.

4

2 回答 2

29

要在主 ipython 命名空间中运行脚本:

ipython script.py

当然,这只是运行并退出。如果要在主 ipython 命名空间中运行脚本,然后放入 REPL:

ipython -i script.py

如果您已经在 ipython 中并且想要在现有的主 ipython 命名空间中运行脚本:

%run -i script.py

您可能需要添加其他参数——例如,如果您的脚本sys.exit在任何地方显式调用,您可能需要一个-e参数。

如果您只想在不运行“活动”代码的情况下将所有名称导入您的命名空间,您可以%run -n -i script.py在脚本进行if __name__ == '__main__'测试时执行此操作。

当然,即使没有 ipython,您也可以execfile('script.py')使用几乎完全相同的效果(除了与本地人的一些奇怪的交互,并且在 3.x 中不工作)。甚至from script import *可能足够接近。

于 2012-11-09T01:20:22.697 回答
2

您似乎想要的是为了开发目的打破范围,使本地人成为全局人,这可能不是最好的主意。

作为一种可能的选择,你知道ipdb吗?

于 2012-11-09T00:38:04.230 回答