How can you save functions/ classes you’ve writing in a python interactive session to a file? Specifically, is there a way in pydev / eclipse’s interactive session (on a mac) to do this?
I just started learning python – and am enjoying using the interpreter’s interactive session for testing and playing with modules I’ve written. However, I find myself writing functions in the interpreter, which I think, oh it would be cool to save that to my script files. How do I do this?
I tried:
import pickle
pickle.dump(my_function, open("output.p", "w"))
But it seems to be more of a binary serialization, or at least nothing that I could copy and paste into my code…
Are there ways to see the code behind classes & functions I’ve defined in the interpreter? And then copy them out of the interpreter?
Update:
Ok, here’s what I’ve learned so far:
- I missed the easiest of all – PyDev’s interactive session in eclipse allows you to right click and save your session. Still have to remove >>>’s, but gets the job done.
- IPython is apparently the way to go to do this.
- How to save a Python interactive session? has more details.
The best environment for interactive coding sessions has to be IPython, in my opinion. It’s built on and extends the basic Python interpreter with a lot of magic, including history. For example, you can issue the command %logstart to dump all subsequent input to a file, which still needs to be edited afterward before it will be a script, but gives you a lot to work with.
When installing IPython, don’t forget pyreadline.
In general, however, it is best to write code in an IDE and then run it. IPython helps here as well. If you write and save the script, then use the IPython “run” command to run it, the entire global namespace of the script will be available for inspection in your IPython session. Additionally, you can use the -d argument to run to trigger the pdb debugger immediately on any unhandled exception.
If you’re more of a straightlaced IDE and debugger kind of guy, then the easiest and best lightweight environment has to be PyScripter.