views:

285

answers:

5

Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?

Edit: I guess I should clarify by specifying why I want to do this. I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into REPL to allow for the plot to be customized.

+3  A: 

You can launch the debugger:

import pdb;pdb.set_trace()

Not sure what you want the REPL for, but the debugger is very similar.

Ned Batchelder
I would suspect that he would like to make live changes to a running process, à la Lisp.
Pinochle
+5  A: 

Here's how you should do it:

from IPython.Shell import IPShellEmbed

ipshell = IPShellEmbed()

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

You should use IPython, the Cadillac of Python REPLs. See http://ipython.scipy.org/doc/stable/html/interactive/reference.html#embedding-ipython

From the documentation:

It can also be useful in scientific computing situations where it is common to need to do some automatic, computationally intensive part and then stop to look at data, plots, etc. Opening an IPython instance will give you full access to your data and functions, and you can resume program execution once you are done with the interactive part (perhaps to stop again later, as many times as needed).

joeforker
IPython is great, but if the OP wants a solution that only uses built-in Python, Jason's code.InteractiveConsole() solution is how you "should" do it. :-)
benhoyt
+2  A: 

You could try using the interactive option for python:

python -i program.py

This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.

Alex
When you're ready to switch to the dark side, ipython -i program.py is there for you.
joeforker
+5  A: 

I frequently use this:

def interact():
 import code
 code.InteractiveConsole(locals=globals()).interact()
Jason R. Coombs
Docs for the "code" module are here: http://docs.python.org/library/code.html
benhoyt
You can do it even simpler than that: import code; code.interact(local=locals())
lost-theory
A: 

to get goodnes of iPython and functionaly of debugger you should use ipdb,

you can use it in the same way as pdb, but:

import ipdb
ipdb.set_strace()

link text

bluszcz