python - 当用户关闭程序/脚本时如何创建文件?
问题描述
基本上,我正在尝试创建一个脚本文件,该文件记录我正在编码和写入的任何内容,并将文件保存到当前目录,无论何时我直接关闭编辑器或关闭时。
有没有办法做到这一点?
我尝试过的事情:
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)
退出函数不会在此处触发。
解决方案
推荐阅读
- javascript - javascript fetch API 中是否有等效的“curl -v”?
- r - 如何使用 `tempdisagg` 包中的 `td` 命令将每月数据分解为每日数据频率?
- django - 为什么我的文字帖子无法保存,它以前工作过?
- amazon-web-services - Redshift 增强型 VPC 路由
- c++ - 未构建具有第三方库的项目
- ruby - 使用硒进行 RSpec 系统测试 - 允许访问相机
- java - 直接调用 `mvn package` 有效,但通过 Makefile 失败
- java - 如何在 Java 8 中循环遍历字节数组?
- java - Java 日期时间为 ISO_DATE_TIME
- mysql - 无法执行字符串到日期的转换