Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to go into ipython from code?

For my debugging needs, pdb is pretty good. However, it would be much cooler (and helpful) if I could go into ipython. Is this thing possible?

like image 553
Geo Avatar asked Jul 14 '09 17:07

Geo


People also ask

How do I get into IPython?

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. IPython 0.13.

How do I start IPython from command prompt?

Found the solution: run python -m IPython (case sensitive). To find that out, I ran pip show ipython and it showed me some info, including the path of the module (for me: c:\users\mathieures\appdata\local\packages\pythonsoftwarefoundation. python.

How do I run IPython commands?

If you want some code to be run at the beginning of every IPython session, the easiest way is to add Python (. py) or IPython (. ipy) scripts to your profile_default/startup/ directory. Files here will be executed as soon as the IPython shell is constructed, before any other code or scripts you have specified.


11 Answers

There is an ipdb project which embeds iPython into the standard pdb, so you can just do:

import ipdb; ipdb.set_trace()

It's installable via the usual pip install ipdb.

ipdb is pretty short, so instead of easy_installing you can also create a file ipdb.py somewhere on your Python path and paste the following into the file:

import sys
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
from IPython import ipapi

shell = IPShell(argv=[''])

def set_trace():
    ip = ipapi.get()
    def_colors = ip.options.colors
    Pdb(def_colors).set_trace(sys._getframe().f_back)
like image 96
Daniel Roseman Avatar answered Oct 04 '22 15:10

Daniel Roseman


In IPython 0.11, you can embed IPython directly in your code like this

Your program might look like this

In [5]: cat > tmpf.py
a = 1

from IPython import embed
embed() # drop into an IPython session.
        # Any variables you define or modify here
        # will not affect program execution

c = 2

^D

This is what happens when you run it (I arbitrarily chose to run it inside an existing ipython session. Nesting ipython sessions like this in my experience can cause it to crash).

In [6]:

In [6]: run tmpf.py
Python 2.7.2 (default, Aug 25 2011, 00:06:33)
Type "copyright", "credits" or "license" for more information.

IPython 0.11 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: who
a       embed

In [2]: a
Out[2]: 1

In [3]:
Do you really want to exit ([y]/n)? y


In [7]: who
a       c       embed
like image 32
Alex Gaudio Avatar answered Oct 04 '22 13:10

Alex Gaudio


If you're using a more modern version of IPython (> 0.10.2) you can use something like

from IPython.core.debugger import Pdb
Pdb().set_trace()

But it's probably better to just use ipdb

like image 37
chrisdev Avatar answered Oct 04 '22 15:10

chrisdev


The equivalent of

import pdb; pdb.set_trace()

with IPython is something like:

from IPython.ipapi import make_session; make_session()
from IPython.Debugger import Pdb; Pdb().set_trace()

It's a bit verbose, but good to know if you don't have ipdb installed. The make_session call is required once to set up the color scheme, etc, and set_trace calls can be placed anywhere you need to break.

like image 35
ars Avatar answered Oct 04 '22 13:10

ars


Normally, when I use ipython, I turn automatic debugging on with the "pdb" command inside it.

I then run my script with the "run myscript.py" command in the directory where my script is located.

If I get an exception, ipython stops the program inside the debugger. Check out the help command for the magic ipython commands (%magic)

like image 34
Jay Atkinson Avatar answered Oct 04 '22 15:10

Jay Atkinson


I like to simply paste this one-liner in my scripts where I want to set a breakpoint:

__import__('IPython').Debugger.Pdb(color_scheme='Linux').set_trace()

Newer version might use:

__import__('IPython').core.debugger.Pdb(color_scheme='Linux').set_trace()
like image 41
xApple Avatar answered Oct 04 '22 14:10

xApple


Looks like modules have been shuffled around a bit recently. On IPython 0.13.1 the following works for me

from IPython.core.debugger import Tracer; breakpoint = Tracer()

breakpoint() # <= wherever you want to set the breakpoint

Though alas, it's all pretty worthless in qtconsole.

like image 31
beardc Avatar answered Oct 04 '22 15:10

beardc


Newer versions of IPython provide an easy mechanism for embedding and nesting IPython sessions into any Python programs. You can follow the following recipe to embed IPython sessions:

try:
    get_ipython
except NameError:
    banner=exit_msg=''
else:
    banner = '*** Nested interpreter ***'
    exit_msg = '*** Back in main IPython ***'

# First import the embed function
from IPython.frontend.terminal.embed import InteractiveShellEmbed
# Now create the IPython shell instance. Put ipshell() anywhere in your code
# where you want it to open.
ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)

Then use ipshell() whenever you want to drop into an IPython shell. This will allow you to embed (and even nest) IPython interpreters in your code.

like image 33
Amelio Vazquez-Reina Avatar answered Oct 04 '22 13:10

Amelio Vazquez-Reina


From the IPython docs:

import IPython.ipapi
namespace = dict(
    kissa = 15,
    koira = 16)
IPython.ipapi.launch_new_instance(namespace)

will launch an IPython shell programmatically. Obviously the values in the namespace dict are just dummy values - it might make more sense to use locals() in practice.

Note that you have to hard-code this in; it's not going to work the way pdb does. If that's what you want, DoxaLogos' answer is probably more like what you're looking for.

like image 44
David Z Avatar answered Oct 04 '22 13:10

David Z


The fast-and-easy way:

from IPython.Debugger import Tracer
debug = Tracer()

Then just write

debug()

wherever you want to start debugging your program.

like image 21
Viktiglemma Avatar answered Oct 04 '22 13:10

Viktiglemma


I had to google this a couple if times the last few days so adding an answer... sometimes it's nice to be able run a script normally and only drop into ipython/ipdb on errors, without having to put ipdb.set_trace() breakpoints into the code

ipython --pdb -c "%run path/to/my/script.py --with-args here"

(first pip install ipython and pip install ipdb of course)

like image 20
Anentropic Avatar answered Oct 04 '22 15:10

Anentropic