Qyouu
设置自己的信号处理程序的另一种方法是使用上下文管理器来捕获异常并忽略它:>>> class CleanExit(object):... def __enter__(self):... return self... def __exit__(self, exc_type, exc_value, exc_tb):... if exc_type is KeyboardInterrupt:... return True... return exc_type is None... >>> with CleanExit():... input() #just to test it... >>>这将删除try- except块,同时保留一些明确的说明。这也允许您仅在代码的某些部分中忽略中断,而不必每次都设置和重置信号处理程序。