python - 关闭 python 脚本之前的操作

标签 python

你好,我有一个 python 脚本,它在无限循环中运行一些 Action ,但有时我必须关闭脚本并用新版本更新它,在服务器上做一些工作,等等。

问题是,我怎样才能停止脚本并在关闭它之前,脚本在循环后执行一些操作,如关闭 sqlite 连接、关闭与代理的连接等。

我现在做的是 ctr+c 直到它停止(在它完成之前需要几次)然后手动关闭 sqlite 连接等。

最佳答案

您可以捕获信号并执行 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)

关于python - 关闭 python 脚本之前的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33084356/

相关文章:

python - Pandas 中基于行计算的有效方法

python - Flask render_template 上下文在蓝图中为 None

python - Gunicorn 和 Flask 蓝图

python - numpy 中的数组索引

python - 使用 Python 2.7 脚本 : I/O handling 调用需要通过 GUI 输入的 Windows 应用程序

python:将父类中的每个方法包装在 "with"中的最干净的方法

Python 调用模块

python - 如何在前端表单中使用 django-wysihtml5?

python - 索引具有多个条件的 Python Pandas 数据框 SQL like where 语句

python - 如何动态地将value设置为复杂的json内容,接收key(或key路径)和value作为参数