Hi i have an script in python that run in a infinite loop some actions, but sometimes i have to close the script and update it with a new version, make some works in the server, etc.
The question, is how can i do to stop the script and before close it, the script make some actions after the loop as close sqlite connection, close connection with a broker, etc.
what i do now is ctr+c until it stop (take few times before it finish) and then manually close sqlite connection, etc.
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 Event.wait() With time.sleep() , your code will need to wait for the Python sleep() call to finish before the thread can exit.
However, once Python exits from the “with” block, the file is automatically closed.
You can catch a signal an execute something other then sys.exit
import signal
import sys
def signal_handler(signal, frame):
print 'You pressed Ctrl+C - or killed me with -2'
#.... Put your logic here .....
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
You could use the atexit module:
import atexit
def cleanup():
print "cleanup"
# close connections, ...
atexit.register(cleanup)
The cleanup()
function will be called on every normal termination (this includes Ctrl-C).
You could use a try-except
block around your loop and catch the KeyboardInterrupt
exception. Or a finally
block to also clean up if the program terminates in an orderly fashion. Your code should then look something like this:
try:
<your loop goes here>
except KeyboardInterrupt:
<handle error and do possible special cleanup>
finally:
<do the cleanup that always has to happen>
Note that this way you only handle the case when you kill your script with a keyboard interrupt and no other case.
You could also used the with
statement see here for more info (as mentioned in the comments)
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