Zak
Zak

Reputation: 3253

How to stop a Python script but keep interpreter going

I have a Python script, and I want to execute it up to a certain point, then stop, and keep the interpreter open, so I can see the variables it defines, etc.

I know I could generate an exception, or I could invoke the debugger by running pdb.set_trace(), then stop the debugger, which is what I currently use.

...but is there a command that will just stop the script, as if it had simply reached its end? This would be equivalent to commenting the entire rest of the script (but I would not like doing that), or putting an early return statement in a function.

It seems as if something like this has to exist but I have not found it so far.

Edit: Some more details of my usecase

I'm normally using the regular Python consoles in Spyder. IPython seems like a good thing but ( at least for the version I'm currently on, 2.2.5) some of the normal console's features don't work well in IPython (introspection, auto-completion). More often than not, my code generates matplotlib figures. In debug mode, those cannot be updated (to my knowledge), which is why I need to get completely out of the script, but not the interpreter). Another limit of the debugger is that I can't execute loops in it: you can copy/paste the code for a loop into the regular console and have it execute, but that won't work in the debugger (at least in my Spyder version).

Upvotes: 11

Views: 9136

Answers (3)

cadolphs
cadolphs

Reputation: 9617

If you have ipython (highly, highly recommended), you can go to any point in your program and add the following lines

import IPython
IPython.embed()

Once your program reaches that point, the embed command will open up a new IPython shell within that context.

I really like to do that for things where I don't want to go the full pdb route.

Upvotes: 12

jasonharper
jasonharper

Reputation: 9597

If you invoke your program with python -i <script>, the interpreter will remain active after the script ends. raise SystemExit would be the easiest way to force it to end at an arbitrary point.

Upvotes: 18

GantTheWanderer
GantTheWanderer

Reputation: 1292

If you are using the Python Shell, just press CTRL + C to throw a KeyboardInterrupt. You can then check out the state of the program at the time the exception was throw.

x = 0
while True:
    x += 1

Running the script...

Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================

Traceback (most recent call last):

File "C:/Python27/test.py", line 2, in

while True:

KeyboardInterrupt

>>> x

15822387

Upvotes: 3

Related Questions