drop into python interpreter while executing function

Python

Python Problem Overview


i have a python module with a function:

def do_stuff(param1 = 'a'):
    if type(param1) == int:
        # enter python interpreter here
        do_something()
    else:
        do_something_else()

is there a way to drop into the command line interpreter where i have the comment? so that if i run the following in python:

>>> import my_module
>>> do_stuff(1)

i get my next prompt in the scope and context of where i have the comment in do_stuff()?

Python Solutions


Solution 1 - Python

If you want a standard interactive prompt (instead of the debugger, as shown by prestomation), you can do this:

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

See: the code module.

If you have IPython installed, and want an IPython shell instead, you can do this for IPython >= 0.11:

import IPython; IPython.embed()

or for older versions:

from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell(local_ns=locals())

Solution 2 - Python

Inserting

import pdb; pdb.set_trace()

will enter the python debugger at that point

See here: http://docs.python.org/library/pdb.html

Solution 3 - Python

If you want a default Python interpreter, you can do

import code
code.interact(local=dict(globals(), **locals()))

This will allow access to both locals and globals.

If you want to drop into an IPython interpreter, the IPShellEmbed solution is outdated. Currently what works is:

from IPython import embed
embed()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaaronstacyView Question on Stackoverflow
Solution 1 - PythonMatt AndersonView Answer on Stackoverflow
Solution 2 - PythonprestomationView Answer on Stackoverflow
Solution 3 - PythonRonan PaixãoView Answer on Stackoverflow