I'm running my Python program and have a point where it would be useful to jump in and see what's going on, and then step out again. Sort of like a temporary console mode.

In Matlab, I'd use the keyboard command to do this, but I'm not sure what the command is in python.

Is there a way to do this?

For instance:

for thing in set_of_things:

enter_interactive_mode_here()

do_stuff_to(thing)

When enter_interactive_mode() calls, I'd like to go there, look around, and then leave and have the program continue running.

解决方案

code.interact() seems to work somehow:

>>> import code

>>> def foo():

... a = 10

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

... return a

...

>>> foo()

Python 3.6.5 (default, Apr 1 2018, 05:46:30)

[GCC 7.3.0] on linux

Type "help", "copyright", "credits" or "license" for more information.

(InteractiveConsole)

>>> a

10

Ctrl+Z returns to the "main" interpreter.

You can read the locals, but modifying them doesn't seem to work this way.