python 捕获 ctrl c中断信号

训练model时可能会在中间时刻停止训练,如果想要停止信号发出后,继续执行剩下的代码,可以使用下述方式:

	try:
		model.learn(total_timesteps=int(trian_steps), callback=callback)
	except KeyboardInterrupt:
		model.save(log_dir + "{}-{}-{}".format(algo, env_name, trian_steps))
		results_plotter.plot_results([log_dir], trian_steps, results_plotter.X_TIMESTEPS, "{}, {}".format(algo, env_name))
		plt.savefig(log_dir + "{}-{}-{}.png".format(algo, env_name, trian_steps))
		# plt.show()
		print('{} {} training finished.'.format(algo, env))

或者使用signal模块

import signal

def exit(signum, frame):
  print('You choose to stop me.')
  exit()

signal.signal(signal.SIGINT, exit)
signal.signal(signal.SIGTERM, exit)

while 1:
  print('running......)

你可能感兴趣的:(python 捕获 ctrl c中断信号)