Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

ipython

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?

like image 927
user3208430 Avatar asked Jan 29 '14 02:01

user3208430


People also ask

How do I turn on interactive mode 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 start IPython from command-line?

You start IPython by typing “ipython” in your terminal. $ ipython Python 2.7. 2 (default, Jun 20 2012, 16:23:33) Type "copyright", "credits" or "license" for more information.

How do I run a Python program in IPython?

You can use run command in the input prompt to run a Python script. The run command is actually line magic command and should actually be written as %run. However, the %automagic mode is always on by default, so you can omit this.

What is IPython interactive?

IPython (Interactive Python) is a command shell for interactive computing in multiple programming languages, originally developed for the Python programming language, that offers introspection, rich media, shell syntax, tab completion, and history.


1 Answers

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()
like image 149
Cody Piersall Avatar answered Sep 29 '22 10:09

Cody Piersall