Python - How to detect when user closes a console application via “X” button

China☆狼群 提交于 2019-11-29 14:28:28
Ben DeMott

In windows

if you are using pywin32, you can perform an event before the console is closed, I'm not sure this will tell you who or what is closing it, but maybe this gets you half way. You might also want to check out: Prevent a console app from closing ...

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!