使用信号处理方式解决,上代码:
import signal import sys import time # 信号处理程序Ctrl+C signal.signal(signal.SIGINT, lambda *_: sys.exit(0)) while True: print("Waiting...") print(time.ctime()) time.sleep(2)