blog/source/_posts/Python/Python捕获Ctrl+C手工终止程序的方法.md
2022-08-31 15:23:30 +08:00

23 lines
525 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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