2016-11-29 182 views
3

我有一个在后台运行的python进程,我希望它只在脚本终止时才生成一些输出。当python进程死亡时运行atexit()

def handle_exit(): 
    print('\nAll files saved in ' + directory) 
    generate_output() 

atexit.register(handle_exit) 

调用养KeyboardInterupt例外,sys.exit()电话handle_exit()正常,但如果我从终端做kill {PID}则终止该脚本,而无需调用handle_exit()。

有没有办法终止在后台运行的进程,并且在终止之前仍然运行handle_exit()

+1

单独使用atexit不可能。正如文档所指出的那样'当程序被非Python处理的信号终止时,当检测到Python致命内部错误或调用os._exit()时,不会调用通过此模块注册的函数。“[here] (https://docs.python.org/2/library/atexit.html) –

回答

5

尝试signal.signal。它可以捕捉任何系统的信号:

import signal 

def handle_exit(): 
    print('\nAll files saved in ' + directory) 
    generate_output() 

atexit.register(handle_exit) 
signal.signal(signal.SIGTERM, handle_exit) 
signal.signal(signal.SIGINT, handle_exit) 

现在你可以kill {pid}handle_exit将被执行。

+0

谢谢,这正是我正在寻找的。 –