blog/source/_posts/Python/Python捕获Ctrl+C手工终止程序的方法.md

25 lines
517 B
Markdown
Raw Normal View History

2022-08-31 07:23:30 +00:00
---
title: Python 捕获 Ctrl+C 手工终止程序的方法
date: 2022-08-31 15:13:08
2022-09-03 09:45:34 +00:00
categories:
- Python
keywords:
- Python
tags:
- Python
2022-08-31 07:23:30 +00:00
---
日常编写调试运行程序过程中,难免需要手动终止程序。可以使用以下的方法捕获 KeyboardInterrupt从而优雅地终止程序的运行。
``` python
import sys, time
try:
while True:
# # DO THINGS ....
time.sleep(1)
except KeyboardInterrupt:
# QUIT with Ctrl+C 在这里处理善后工作
sys.exit()
```