Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython Maintain namespace after run

Tags:

python

ipython

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.

like image 537
virati Avatar asked Nov 09 '12 00:11

virati


1 Answers

To run a script in the main ipython namespace:

ipython script.py

Of course this just runs and exits. If you want to run the script in the main ipython namespace and then drop into the REPL:

ipython -i script.py

If you're already inside ipython and you want to run the script in the existing main ipython namespace:

%run -i script.py

You may need to add other params—e.g., if your script explicitly calls sys.exit anywhere, you probably want a -e param.

If you just want to import all of the names into your namespace without running the "active" code, you can do %run -n -i script.py if the script does the if __name__ == '__main__' test.

Of course even without ipython, you can execfile('script.py'), with almost exactly the same effect you're looking for (except for some weird interactions with locals, and not working in 3.x). Or even from script import * may be close enough.

like image 190
abarnert Avatar answered Nov 06 '22 06:11

abarnert