Robert Pollak
Robert Pollak

Reputation: 4165

How to exit a script in 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?

Upvotes: 8

Views: 31534

Answers (5)

Robert Pollak
Robert Pollak

Reputation: 4165

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
    

Upvotes: 15

Francisco C
Francisco C

Reputation: 381

Solution that works for me: On windows with Spyder 5 installed. I run Spyder from an Anaconda PowerShell Prompt, so when Spyder stalls, I can go to the shell and use Ctrl+c to kill any process.

Upvotes: -2

bhushan
bhushan

Reputation: 11

Built-in solution can be used:

import sys

sys.exit()

Upvotes: 1

Dmitry dich63
Dmitry dich63

Reputation: 1

To interrupt the execution of Spyder without warning, you can call

raise SystemExit(0)

Upvotes: -1

ollydbg23
ollydbg23

Reputation: 1200

As Robert Pollak suggest, the comment in Spyderlib Issue 1974 #4 is a better solution. Just define a function which cause an exception, and call this function if you want to stop the execute of script inside spyder.

def f(): raise Exception("Found exit()")

Upvotes: 4

Related Questions