Python 检查是否强制关闭 [英] Python check if force closed

查看:60
本文介绍了Python 检查是否强制关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在终端窗口中运行了一个 python 文件program.py".当运行它的窗口被手动终止时,我需要该程序将诸如强制关闭"之类的内容记录到文件中.我已经读到该程序会发送一个 -1 的状态代码来表示执行失败,但是我如何阅读并基于此执行某些操作?

Suppose I have a python file 'program.py' running in a terminal window. I need that program to log something like say 'force closed' to a file when the window in which it was running was terminated manually. I've read that the program sends a status code of -1 for unsuccessful execution, but how do I read and do something based on that?

推荐答案

你不能.进程无法读取自己的退出代码.那没有多大意义.但是为了强制进程关闭,操作系统必须向该进程发送信号.只要它不是 SIGKILL 和/或 SIGSTOP 那么你就可以通过 signal 图书馆.SIGKILL 和 SIGSTOP 不能被阻塞,例如如果有人kill -9 那么你就无能为力了.

You can't. A process can't read it's own exit code. That would not make much sense. But in order to force process shutdown the OS has to send a signal to that process. As long as it is not SIGKILL and/or SIGSTOP then you can intercept it via signal library. SIGKILL and SIGSTOP cannot be blocked, e.g. if someone does kill -9 then there's nothing you can do.

使用信号库:

import signal
import sys

def handler(signum, frame):
    # do the cleaning if necessary

    # log your data here
    with open('log.log', 'a') as fo:
        fo.write('Force quit on %s.\n' % signum)

    # force quit
    sys.exit(1)  # only 0 means "ok"

signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGTERM, handler)

当终端关闭时,它会向进程发送 SIGHUP.

When terminal closes it sends SIGHUP to a process.

SIGINT 用于 CTRL-C 中断.

SIGINT is used for CTRL-C interruption.

SIGTERM 类似于 SIGKILL.不同之处在于进程可以捕获它.这是一个优雅的杀戮".

SIGTERM is similar to SIGKILL. The difference is that the process can catch it. It's a "graceful kill".

重要提示:这适用于所有 POSIX 系统.我不太了解其他操作系统.

IMPORTANT: This is true for all POSIX systems. I don't know much about other OS.

这篇关于Python 检查是否强制关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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