如何防止 Python 脚本强制退出? [英] How to prevent Python script from Force exit?
问题描述
我正在运行一个 python 脚本并试图防止强制退出或打印错误消息或将其记录到日志文件中.
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.
我已经在使用 logging.info("")
进行日志记录......或者只是使用 print
来打印一些东西......
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?
例如,如果我的 test.py 正在运行并且我按 Ctrl + C 退出.. 我想记录或打印出来..
For example, if my test.py is running and I press Ctrl + C to exit out.. I want to log that or print out..
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")
当我想退出程序时,我正在使用上面的代码进行记录.但这并没有处理诸如 ctrl + c
之类的事情,我也想登录以防万一程序意外退出或其他事情
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
推荐答案
UPDATED
使用 try 和 except:
Use try and except:
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))
您还可以利用 atexit
模块在脚本退出时执行函数.
You could also leverage the atexit
module to execute a function when the script exits.
import atexit
def alldone():
log.warning('Something went wrong')
# your code here...
https://docs.python.org/2/library/atexit.html
这篇关于如何防止 Python 脚本强制退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!