拦截 python 脚本完成

Intercept python script completion

有什么方法可以拦截 python 脚本的完成,如果可以,该怎么做?在完成之前使用某种代码?脚本可以简单地通过关闭十字或 ctrl + c

来结束

我建议使用 context manager

class Context(object):
    def __enter__(self):
        pass

    def __exit__(self, type, value, trace):
        print("Ending")

with Context():
    print("script")

这将 运行 程序结束时 __exit__ 函数中的任何内容,即使它提前终止。

如果您在 __enter__ 函数中添加内容,它将 运行 放在脚本的开头。