In the following simple example, I have a function foo() do something. There is a variable a inside the function. What I would like to do is that when the program catch the KeyboardInterrupt, the local functional variable a can be printed.
Clearly, the following way is not working. Is there anyway can do this?
def foo():
a = 1
for _ in xrange(10000):
a += 1
return a
try:
a = foo()
except KeyboardInterrupt:
print a
Updates (answer some comments below regarding why I want to Control-C):
Actually, my intention is to stop my Keras RNN training process earlier. Like the following code:
from keras.models import Sequential
def train():
model = Sequential()
....
model.build()
....
for iteration in range(1, 200):
....
model.fit(X_train, y_train, ...)
....
....
if __name__ == '__main__':
try:
model = train()
except KeyboardInterrupt:
model.save_weights("weights.hdf5")
If I stop the training process early, I would like to save the current model weights.
Control-CorDelete)". so do do you really want this or when the user press any key instead?Control-C, please see my question updates.