Ibrahim Muhammad
Ibrahim Muhammad

Reputation: 2896

Resume code execution from code.interact() in Python

After opening an interactive console while debugging using

code.interact(local=locals())

How can I resume code execution. I have checked the docs for the 'code' module and search stack overflow but cannot find anything.

Upvotes: 11

Views: 5220

Answers (3)

shadowbq
shadowbq

Reputation: 1459

If you want to use code snippets in your IDE (vscode, etc), in python3 the contextlib.suppress() is a great way to make your debug snippet a one-liner so you can continue with exit().

# At the top of you code
import code
from contextlib import suppress
# At the point of debugging
need_to_debug = 'lorem ipsum'
with suppress(SystemExit): code.interact(local=dict(globals(), **locals()))

Upvotes: 0

kindall
kindall

Reputation: 184141

It's the same way you exit any Python interpreter session: send an end-of-file character.

That's Ctrl-D on Linux or Ctrl-Z Enter on Windows.

Upvotes: 17

Cody Piersall
Cody Piersall

Reputation: 8547

If like me you always forget to hit Ctrl-D, you can wrap up your prompt in a try/except block:

try:
    code.interact(local=locals())
except SystemExit:
    pass

Upvotes: 7

Related Questions