Skip to content

Instantly share code, notes, and snippets.

@stevekm
Last active March 10, 2024 14:49
Show Gist options
  • Save stevekm/084904836a8a210067660cc4374f4818 to your computer and use it in GitHub Desktop.
Save stevekm/084904836a8a210067660cc4374f4818 to your computer and use it in GitHub Desktop.
Start an interactive Python shell session from within a script

from here: http://stackoverflow.com/questions/5597836/embed-create-an-interactive-python-shell-inside-a-python-program

paste this inside your script for debugging, to start a Python interactive terminal shell session at that point in the script, super useful for debugging since it lets you explore the Python environment and access objects and variables as they are at that point in the script.

import readline # optional, will allow Up/Down/History in the console
import code
vars = globals().copy()
vars.update(locals())
shell = code.InteractiveConsole(vars)
shell.interact()

Here's a handy function to use with it:

def my_debugger():
    # DEBUGGING !!
    # call with my_debugger() anywhere in your script
    import readline # optional, will allow Up/Down/History in the console
    import code
    vars = globals().copy()
    vars.update(locals())
    shell = code.InteractiveConsole(vars)
    shell.interact()

But if you embed this function into a module that is loaded by Python, you have to take one more step

# in the module file
def my_debugger(vars):
    # starts interactive Python terminal at location in script
    # call with pl.my_debugger(globals().copy()) anywhere in your script
    import readline # optional, will allow Up/Down/History in the console
    import code
    # vars = globals().copy() # in python "global" variables are actually module-level
    vars.update(locals())
    shell = code.InteractiveConsole(vars)
    shell.interact()
# in the script which loads the module
my_module.my_debugger(globals().copy())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment