Quick-tip: Embedding python shells in your scripts

written on 22 Jul 2017

python

shell

quicktip

ipython


When I write a python script, or package I often use lots of print() statements and logging-functions to give med feedback on what the state of a variable is. I then change some part of the code and run the script again…

This is fine, but I recently found out you can embed an interactive python shell in your scripts. This makes it possible to interactivly work with functions and variables that is in the context of your script or package.

I’m probably very late to the party, but I wanted to share regardless. Just in case some people wasn’t aware.

I discovered this doing a simple google search. The first link was (obviously) to a stackoverflow question. (the post is old I know) The stackoverflow post shows the ways to start an interactive shell with and without IPython. IPython has pretty good documentation on this feature on their site.

You can start the shell at any point in the code with two lines using IPython and six lines with the built-in package in Python.

from IPython import embed
from hack import the_world

embed() # this call anywhere in your program will start IPython

The six-lines can be found in this stackoverflow answer. To get it working with Python 3 you have to remove the import readline statement. Like so:

import code
vars = globals().copy()
vars.update(locals())
shell = code.InteractiveConsole(vars)
shell.interact()

If you’ve ever used Django you have most likely used this at some point.

Fun-ish-fact: Even though this was a quicktip, it took me almost two weeks to finish and publish this.