How to stop Python script, but continue interpreter translation

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

I know I can throw an exception, or I could call the debugger by running pdb.set_trace() and then stop the debugger that I am currently using.

... but is there a command that just stops the script as if it just reached the end? This would be equivalent to commenting out the rest of the script (but I would not want to do this), or putting an early return in a function.

It seems like something like this should exist, but I haven't found it yet.

Edit: some details of my use

I usually use regular Python consoles in Spyder. IPython looks pretty good, but (at least for the version I'm currently on, 2.2.5) some of the usual console functions do not work well in IPython (introspection, autocomplete). Most often, my code generates matplotlib numbers. In debug mode, these updates cannot be updated (as far as I know), so I need to completely exit the script, but not the interpreter). Another limit of the debugger is that I cannot execute loops in it: you can copy / paste the code for the loop into a regular console and execute it, but this will not work in the debugger (at least in my Spyder version).

+5
source share
3 answers

If you invoke your program using python -i <script> , the interpreter will remain active after the script completes. raise SystemExit would be the easiest way to make it finish at an arbitrary point.

+6
source

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

 import IPython IPython.embed() 

Once your program reaches this point, the embed command will open a new IPython shell in this context.

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

+4
source

If you are using a Python shell, just press CTRL + C to throw away KeyboardInterrupt. Then you can check the status of the program during the exception throw.

 x = 0 while True: x += 1 

Running script ...

Python 2.7.6 (default, November 10, 2013 7:24:18 PM) [MSC v.1500 32 bit (Intel)] on win32 Enter “copyright”, “credits” or “license ()” for more information . →> ========================= RESTART ====================== ==================================================== ================

Traceback (last last call):

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

and True:

KeyboardInterrupt

→> x

15822387

+1
source

Source: https://habr.com/ru/post/1263068/


All Articles