首页 > 解决方案 > 当用户关闭程序/脚本时如何创建文件?

问题描述

基本上,我正在尝试创建一个脚本文件,该文件记录我正在编码和写入的任何内容,并将文件保存到当前目录,无论何时我直接关闭编辑器或关闭时。

有没有办法做到这一点?

我尝试过的事情:

def save_file():
    open("transcript.txt", "w+")

def set_exit_handler(func):
    if os.name == "nt":
        try:
            import win32api
            win32api.SetConsoleCtrlHandler(func, True)
        except ImportError:
            version = ".".join(map(str, sys.version_info[:2]))
            raise Exception("pywin32 not installed for Python" + version)
    else:
        import signal
        signal.signal(signal.SIGTERM, func)

def on_exit(sig, func=None):
        print("exit handler triggered")
        save_file()
        import time
        time.sleep(5)


set_exit_handler(on_exit)

退出函数不会在此处触发。

标签: pythonpython-3.xwindowshandlerexit

解决方案


推荐阅读