推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
KIRAYOMATO
V2EX  ›  Python

怎么让 Python 程序在被关掉的时候自动执行一个函数?

  •  
  •   KIRAYOMATO · Oct 2, 2024 · 6481 views
    This topic created in 776 days ago, the information mentioned may be changed or developed.
    GPT 说用 SIGNAL 或 win32api 捕捉关闭信号,但是我试了一下都只能在用 Ctrl+C 关闭的时候能成功触发。我想要能在直接把 python 的窗口关掉的时候也能执行这个功能
    8 replies  •  2024-10-17 17:51:00 +08:00
    KIRAYOMATO
    KIRAYOMATO
    OP
    Oct 2, 2024
    2
    @nagisaushio 这个方法试了也是直接关掉窗口的话是不会触发的
    ysc3839
    ysc3839
    Oct 2, 2024 via Android❤️1
    3
    Windows 关闭控制台窗口不行,控制台进程退出,系统会直接杀死连接到该控制台下的所有进程。
    要关闭窗口时执行代码,只能自己创建窗口。
    sagaxu
    sagaxu
    Oct 2, 2024 via Android
    4
    父进程做成无窗口模式,创建 Python 子进程,子进程中创建窗口,父进程检测到子进程退出时执行动作。
    SenLief
    SenLief
    Oct 2, 2024
    5
    如果只用 py 实现,那应该只能用子进程,让父进程守护,子进程退出后发出信号让父进程执行。
    wevsty
    wevsty
    Oct 4, 2024
    6
    GUI 程序可以自己处理 WM_CLOSE 消息
    控制台程序如果注册 SIGNAL 不能满足要求,那就只能自己做守护进程。
    R4rvZ6agNVWr56V0
    R4rvZ6agNVWr56V0
    Oct 5, 2024
    7
    4 楼正解
    yxgcdnncj
    yxgcdnncj
    Oct 17, 2024
    8
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)
    用这种方式 检测到关闭信号的时候 做处理
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4231 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 05:52 · PVG 13:52 · LAX 21:52 · JFK 00:52
    ♥ Do have faith in what you're doing.