Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actions before close python script

Tags:

python

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.

like image 848
a.n. Avatar asked Oct 12 '15 15:10

a.n.


People also ask

How do you end 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 I make Python wait before closing?

Using Event.wait() With time.sleep() , your code will need to wait for the Python sleep() call to finish before the thread can exit.

Does Python close files automatically on exit?

However, once Python exits from the “with” block, the file is automatically closed.


3 Answers

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)
like image 86
Vor Avatar answered Sep 26 '22 21:09

Vor


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).

like image 37
TobiMarg Avatar answered Sep 26 '22 21:09

TobiMarg


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)

like image 24
wastl Avatar answered Sep 24 '22 21:09

wastl