Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: run interactive python shell from program

I often have the case that I'll be writing a script, and I'm up to a part of the script where I want to play around with some of the variables interactively. Getting to that part requires running a large part of the script I've already written.

In this case it isn't trivial to run this program from inside the shell. I would have to recreate the conditions of that function somehow.

What I want to do is call a function, like runshell(), which will run the python shell at that point in the program, keeping all variables in scope, allowing me to poke around in it.

How would I go about doing that?

like image 541
Claudiu Avatar asked Oct 06 '11 16:10

Claudiu


People also ask

How do I run an interactive shell script in Python?

The interactive Python mode lets you run your script instantly via the command line without using any code editor or IDE. To run a Python script interactively, open up your command line and type python. Then hit Enter. You can then go ahead and write any Python code within the interactive mode.

What is Python shell or Python interactive shell?

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.

What is the command used to run Python in interactive mode?

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.


2 Answers

import code  code.interact(local=locals()) 

But using the Python debugger is probably more what you want:

import pdb  pdb.set_trace() 
like image 71
Michael Hoffman Avatar answered Sep 18 '22 23:09

Michael Hoffman


By far the most convenient method that I have found is:

import IPython IPython.embed() 

You get all your global and local variables and all the creature comforts of IPython: tab completion, auto indenting, etc.

You have to install the IPython module to use it of course:

pip install ipython 
like image 41
staticd Avatar answered Sep 18 '22 23:09

staticd