blog/source/_posts/Python/Python捕获Ctrl+C手工终止程序的方法.md
2022-09-03 17:45:34 +08:00

517 B
Raw Permalink Blame History

title date categories keywords tags
Python 捕获 Ctrl+C 手工终止程序的方法 2022-08-31 15:13:08
Python
Python
Python

日常编写调试运行程序过程中,难免需要手动终止程序。可以使用以下的方法捕获 KeyboardInterrupt从而优雅地终止程序的运行。

import sys, time

try:
    while True:
        # # DO THINGS ....
        time.sleep(1)
except KeyboardInterrupt:
    # QUIT with Ctrl+C 在这里处理善后工作
    sys.exit()