python - Python:检查程序是否正在关闭
问题描述
全部。
有没有办法使用 Python 检查当前正在运行的脚本是否被请求关闭?例如,如果我按下右上角的 X-Button(关闭程序按钮)来关闭它,或者以任何其他方式结束脚本,脚本可以在结束之前执行一些代码吗?例子:
# script goes here...
if Script_To_Be_Closed: # replace this with an actual line of code.
do_stuff
解决方案
您可以使用多个选项,例如捕获键盘中断,但最简单的是 atexit,它在脚本结束时执行一个函数(实际上除了硬进程终止)。
import atexit
def my_exit_function(some_argument):
// Your exit code goes here
print(some_argument)
if __name__ == '__main__':
atexit.register(my_exit_function, 'some argument', )
// Your script goes here
推荐阅读
- mongodb - com.mongodb.MongoCursorNotFoundException:查询失败,错误代码 -5 和错误消息“在服务器 localhost:27017 上找不到光标” - Pentaho
- swift - 从 viewDidLoad 外部修改 IBOutlet 属性 - Xcode Storyboards
- c# - 如何在发送前将 Outlook 邮件对象作为草稿电子邮件打开?
- javascript - 使用 JavaScript 添加元素时检测 HTML 更改
- verilog - Verilog(有限状态机)中的序列检测器问题
- java - Java - 从 Web 上下文加载文件
- multithreading - 如何确定应用程序中 I/O 的最佳线程数
- python - 从 Keras GradCam 教程的子类模型制作模型时出现“AttributeError:层 cnn_model 没有入站节点”
- python - Conv2D ValueError:logits 和标签必须具有相同的形状((None,2)与(None,1))
- python - 什么函数用于遍历列表列表并仅将特定行打印到控制台?