Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop python script without killing the python process

I would like to know if there is a way of programatically stopping a python script execution without killing the process like we do with this code:

import sys
sys.exit()

It would be the code equivalent to Ctrl+c

like image 527
Santi Peñate-Vera Avatar asked Feb 09 '15 15:02

Santi Peñate-Vera


People also ask

How do you end a Python program without killing it?

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. If the KeyboardInterrupt does not work, then you can send a SIGBREAK signal. On Windows, press CTRL + Pause/Break.

How do I stop a Python script from running?

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.

What is exit () in Python?

_exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc. Note: This method is normally used in the child process after os. fork() system call. The standard way to exit the process is sys. exit(n) method.


1 Answers

Define your own exception,

class HaltException(Exception): pass

and wrap the script in

try:
    # script goes here

    # when you want to stop,
    raise HaltException("Somebody stop me!")

except HaltException as h:
    print(h)
    # now what?
like image 111
Hugh Bothwell Avatar answered Oct 04 '22 20:10

Hugh Bothwell