Is there any way to run one last command before a running Python script is stopped by being killed by some other script, keyboard interrupt etc.
Use the atexit module to register a function that will be called at the end.
import atexit atexit.register(some_function)