Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit a script in Spyder?

Tags:

python

spyder

I am using WinPython's Spyder. When I am creating a new script with the command exit(), and run it there, this command kills the kernel:

It seems the kernel died unexpectedly. Use 'Restart kernel' to continue using this console.

What's the right way to stop a script in this runtime environment?

like image 238
Robert Pollak Avatar asked Sep 19 '14 07:09

Robert Pollak


People also ask

How do you stop a Python Spyder script?

Once you've clicked anywhere in the IPython Console Window (again, the output window), then, once you press ctrl+c, your program will terminate. If the IPython Console doesn't have focus when you press ctrl+c, it won't know you mean to terminate the program, and so it will ignore the ctrl+c.

How do you exit a Python script?

Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.

How do you exit a running code?

Using KeyboardInterrupt If you want to exit the running program, then you need to raise a KeyboardInterrupt to terminate it. For Windows, press CTRL + C.

How do you exit a script in Python 3?

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program from running.


1 Answers

Update: In at least Spyder 5.0.3, the call to sys.exit() does not kill the kernel any more! (Thanks to @bhushan for the info!)

For earlier versions, the following still holds:

To exit the script, one can

  • raise a silent exception with raise SystemExit(0) (without traceback)

  • or a custom exception like raise Exception('my personal exit message')

  • or encapsulate the code into a function (e.g. main) and use return inside.

If one wants to keep the call to exit() in the script, one can

  • Switch to "Execute in a new dedicated Python interpreter" or

  • register an exit handler at the IPython console:

      def exit_handler(): raise Exception("exit()"), get_ipython().ask_exit = exit_handler
    
like image 196
Robert Pollak Avatar answered Sep 20 '22 05:09

Robert Pollak