Enter Interactive Mode In Python Enter Interactive Mode In Python python python

Enter Interactive Mode In Python


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 linuxType "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)>>> a10

Ctrl+Z returns to the "main" interpreter.

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


python -i myapp.py

This will execute myapp.py and drop you in the interactive shell. From there you can execute functions and check their output, with the whole environment (imports, etc.) of myapp.py loaded.

For something more sophisticated - it would be better to use a debugger like pdb, setting a breakpoint. Also, most IDEs (PyDev, PyCharm, Komodo...) have graphical debuggers.


I use pdb for this purpose. I realize Emil already mentioned this in his answer, but he did not include an example or elaborate on why it answers your question.

for thing in set_of_things:    import pdb; pdb.set_trace()    do_stuff_to(thing)

You can read and set variables by starting your command with an exclamation point. You can also move up and down the stack (commands u and d), which InteractiveConsole does not have built-in mechanisms to do.

To have the program continue executing, use the c command. In the above example it will enter the debugger every loop iteration, so you might want to wrap the set_trace() call in an if sentence.