I am running a python script and trying to prevent from force exiting or print an error message or log that into the log file.
I am already using logging.info("")
for logging.. or just print
for printing something..
but what or how do I create a method or function that can either do print or log when it force exit?
For example, if my test.py is running and I press Ctrl + C to exit out.. I want to log that or print out..
JavaScript
x
signal.signal(signal.SIGUSR1, handler)
logging.info("Checked for signal to stop")
if stop:
logging.info("Inside of main if loop for stop signal")
logging.info("Stop signal captured. Exiting the program")
smtpObj.sendmail(sender, receivers, message + "Stop signal captured. Exiting the program")
sys.exit("EXIT SIGNAL CAPTURED: EXITING")
I am using above coding for logging for when I want to exit the program.
But this doesn’t deal with something like ctrl + c
I want to also log just in case program exit by accident or something
Advertisement
Answer
UPDATED
Use try and except:
JavaScript
try:
signal.signal(signal.SIGUSR1, handler)
logging.info("Checked for signal to stop")
if stop:
logging.info("Inside of main if loop for stop signal")
logging.info("Stop signal captured. Exiting the program")
smtpObj.sendmail(sender, receivers, message + "Stop signal captured. Exiting the program")
sys.exit("EXIT SIGNAL CAPTURED: EXITING")
except KeyboardInterrupt as kbe:
log.info(str(kbe))
You could also leverage the atexit
module to execute a function when the script exits.
JavaScript
import atexit
def alldone():
log.warning('Something went wrong')
# your code here...