Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a Python interactive session?

I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like script I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?

like image 251
unmounted Avatar asked Jun 03 '09 23:06

unmounted


People also ask

How do I save interactive mode in Python?

IPython is extremely useful if you like using interactive sessions. For example for your use-case there is the %save magic command, you just input %save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py (to help with this, every line is prefixed by its number).

How do I create an interactive session in Python?

On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.

How do I save a Python shell?

Right-click the Python window and select Save As to save your code either as a Python file (. py) or Text file (. txt). If saving to a Python file, only the Python code will be saved.

What is a Python interactive session?

The Python interactive console (also called the Python interpreter or Python shell) provides programmers with a quick way to execute commands and try out or test code without creating a file.


1 Answers

IPython is extremely useful if you like using interactive sessions. For example for your use-case there is the %save magic command, you just input %save my_useful_session 10-20 23 to save input lines 10 to 20 and 23 to my_useful_session.py (to help with this, every line is prefixed by its number).

Furthermore, the documentation states:

This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.

This allows for example, to reference older sessions, such as

%save current_session ~0/ %save previous_session ~1/ 

Look at the videos on the presentation page to get a quick overview of the features.

like image 167
Ants Aasma Avatar answered Oct 09 '22 04:10

Ants Aasma