Search code examples
pythonipython

How can I start an interactive python/ipython session from the middle of my python program?


I have a python program which first does some tasks, and then in certain conditions goes into an interactive mode, where the user has access to an interactive python console with the current program's scope. Right now I do this using the code module by calling code.InteractiveConsole(globals()).interact('') (see http://docs.python.org/2/library/code.html).

My problem is that the resulting interactive console lacks some functionalities that I usually get with the standard python console (i.e. the one you get by typing 'python' in a terminal), such as remembering the previous command, etc. Is there a way to get that same interactive console in the middle of my python program, or even better yet ipython's interactive console?


Solution

  • Just use IPython.embed() where you're currently using code.InteractiveConsole(globals()).interact('').

    Make sure you're importing IPython before you do that, though:

    import IPython
    # lots of code
    # even more code
    IPython.embed()