Python-如何检测用户何时通过“ X”关闭控制台应用程序纽扣 [英] Python - How to detect when user closes a console application via "X" button

查看:110
本文介绍了Python-如何检测用户何时通过“ X”关闭控制台应用程序纽扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个在Windows下运行的基于控制台的python程序。该程序会将其大部分数据保留在内存中,并定期将数据保存到磁盘,或者当用户通过键盘中断( Ctrl + C )事件关闭应用程序时。

I currently have a Console based python program running under windows. The program maintains most of its data in memory and periodically saves the data to disk, or when the user shuts the application down via a Keyboard interrupt (Ctrl + C) event.

我遇到的问题是,当用户单击控制台窗口右上方的 X按钮时,会话关闭,并且内存中的数据丢失。我要寻找的是事件/信号或挂钩,以便我可以在关闭之前清理内存。

The problem i have is that when a user hits the "X" button at the top right of the console window, the session closes and the data in memory is lost. What i am looking for is an event/signal or hook so that i can clean up the memory before closing down.

我希望在没有任何外部库的情况下做到这一点,虽然如果不可能,我仍然想知道如何做到。

I am hoping to do this without any external libraries, though if this is not possible i'd still like to know how it can be done.

推荐答案

在Windows中



如果您使用的是pywin32,则可以在关闭控制台之前执行一个事件,我不确定这会告诉您关闭它的是谁或什么,但是也许这可以使您减少一半办法。
您可能还想签出:防止控制台应用程序关闭...

import atexit, os
  atexit.register(lambda: os.system("pause"))



并使用Linux ...



当您关闭SSH会话/窗口时,将抛出SIGHUP信号(信号挂断)。

For those who come across this and use Linux...

the SIGHUP signal is thrown (signal hang up) when you close an SSH session/window.

import signal

signal.signal( signal.SIGHUP, handler )

def handler(signum, frame):
  #this is called when the terminal session is closed
  #do logic before program closes
  pass

这篇关于Python-如何检测用户何时通过“ X”关闭控制台应用程序纽扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆