在执行函数时进入 python 解释器

我有一个 python 模块,它有一个函数:

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

有没有一种方法可以进入我有注释的命令行解释器?这样,如果我在 python 中运行以下命令:

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

我得到我的下一个提示在范围和上下文中我有评论在 do_stuff()

32368 次浏览

Inserting

import pdb; pdb.set_trace()

will enter the python debugger at that point

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

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())

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()