Python checks if power is closed

Suppose I have a python file 'program.py' running in a terminal window. I need this program to write something like “force closing” a file when the window in which it was run was manually completed. I read that the program sends a status code of -1 for unsuccessful execution, but how do I read and do something based on this?

+4
source share
2 answers

You can not. A process cannot read its own exit code. It doesn’t make much sense. But for the forced completion of the process, the OS must send a signal to this process. While this is not SIGKILL and / or SIGSTOP, you can intercept it through the signal library. SIGKILL and SIGSTOP cannot be blocked, for example. if someone does kill -9, then you cannot do anything.

To use the signal library:

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)

When the terminal closes, it sends SIGHUP to the process.

SIGINT is used to interrupt CTRL-C.

SIGTERM is similar to SIGKILL. The difference is that the process can catch it. This is a "graceful murder."

IMPORTANT: This is true for all POSIX systems. I do not know much about other OSs.

+5
source

, , , . , , 0 , , , , . , , , script. , 2 script, script, script ( Popen) , script

edit: Linux , , pywin32, , , = > , https://danielkaes.wordpress.com/2009/06/04/how-to-catch-kill-events-with-python/

+1

All Articles