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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With