Python程序在信号处理程序完成运行之前退出

时间:2014-03-02 22:31:01

标签: python signals

我已经注册了一个SIGINT处理程序,以便在我的python程序退出之前保存一些数据。似乎处理程序在完成之前终止。为什么会发生这种情况,我该怎么办呢?

import sys
import signal
import pickle

debug_data = {
    # some hash
}
debug_known_values = {
    # some other hash
}

def exit_run(signal, frame):
    print("Saving debug data...")
    with open("debug_data.pickle", 'wb') as debug_data_file:
       pickle.dump(debug_data, debug_data_file)
       print("done dumping debug data")
    print("Saving debug known values...")
    with open("debug_known_values.pickle", 'wb') as debug_known_values_file:
        pickle.dump(debug_known_values, debug_known_values_file)
        print("done dumping known values")
    print("exiting")
    sys.exit(0)
signal.signal(signal.SIGINT, exit_run)


if __name__ == "__main__":
    input()
    exit_run(None, None)

如果我按 Enter 退出程序,我会得到

Saving debug data...           
done dumping debug data        
Saving debug known values...   
done dumping known values      
exiting   

如果我点击 Ctrl + C

Saving debug data...            
done dumping debug data         
Saving debug known values...    

我在Windows x64上使用python 3.3.2。

1 个答案:

答案 0 :(得分:0)

此问题是由ComEmu引起的。在它完成退出之前它正在杀死这个过程。代码在普通的cmd窗口中工作正常。